Using Swift SpriteKit, making a game like Doodle Jump, I want the platform continuously bouncing from the left side of the screen to the right. What's the best way of doing this?
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
}
}
}