使用Swift SpriteKit制作像Doodle Jump这样的游戏,我希望平台从屏幕左侧不断反弹到右边。这样做的最佳方式是什么?
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
}
}
}
答案 0 :(得分:0)
您可以使用所需的动画创建一个简单的SKAction
序列:
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)