2017-04-19 3 views
0

Mit Swift SpriteKit, ein Spiel wie Doodle Jump, möchte ich die Plattform ständig von der linken Seite des Bildschirms nach rechts springen. Was ist der beste Weg, dies zu tun?Was ist die beste Methode, um die Plattform von links nach rechts zu bewegen und umgekehrt?

import SpriteKit 
import GameplayKit 

class GameScene: SKScene, SKPhysicsContactDelegate { 

    private var player: Player? 
    private var platform: Platform? 

    var playerCategory: UInt32 = 0b1 
    var platformCategory: UInt32 = 0b10 
    var edgeCategory:  UInt32 = 0b100 

    override func didMove(to view: SKView) { 
     physicsWorld.contactDelegate = self 

     //player 
     player = childNode(withName: "Player") as? Player! 
     player?.physicsBody?.categoryBitMask = playerCategory 
     player?.physicsBody?.collisionBitMask = platformCategory | edgeCategory 


     //placed platform 
     platform = childNode(withName: "Platform") as? Platform! 
     platform?.physicsBody?.categoryBitMask = platformCategory 
     platform?.physicsBody?.collisionBitMask = edgeCategory 
     platform?.physicsBody?.applyImpulse(CGVector(dx: 30, dy: 0)) 


     //create frame boundary 
     let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame) 
     borderBody.friction = 0 
     borderBody.restitution = 0 
     borderBody.categoryBitMask = edgeCategory 
     self.physicsBody = borderBody 
    } 

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
     player?.jump() 
     player?.physicsBody?.collisionBitMask = edgeCategory 
    } 

    override func update(_ currentTime: TimeInterval) { 
     changeCollisions() 
     //movePlatform() 
    } 

    func changeCollisions() { 
     if let body = player?.physicsBody { 
      let dy = body.velocity.dy 
      if dy > 0 { 
       // Prevent collisions if the hero is jumping 
       //body.collisionBitMask = 0 
      } 
      else { 
       // Allow collisions if the hero is falling 
       body.collisionBitMask = platformCategory | edgeCategory 
      } 
     } 
    } 

    func movePlatform() { 
     if ((platform?.position.x)! <= /*-(scene?.size.width)!*/ 0) { 
      platform?.position.x += 5 
     } else { 
      platform?.position.x -= 5 
     } 
    } 
} 

Was ich zur Zeit hat (das graue Rechteck ist die Plattform):

+0

auf diesem Werfen Sie einen Blick : http://stackoverflow.com/a/31594616/3402095 – Whirlwind

Antwort

0

Sie können eine einfache SKAction Sequenz mit der gewünschten Animation erstellen:

let duration = 10 // Animation duration in seconds. 
let moveRight = SKAction.moveTo(x: maxX, duration: duration/2) 
let moveLeft = SKAction.moveTo(x: minX, duration: duration/2) 
let moves = SKAction.repeatForever(.sequence([moveRight, moveLeft]) 
platform!.run(moves) 
Verwandte Themen