Rae*_*ker 0 sprite-kit skphysicsbody swift
所以我一直在做一个游戏,并有一个目前正在运行的小精灵.每当用户点击屏幕躲避障碍物时,我都需要让他跳起来.他跳起后我也需要他回到他的起点.
你可以试试这样的东西!
import SpriteKit
class GameScene: SKScene {
var player: SKSpriteNode?
override func didMove(to view: SKView) {
player = self.childNode(withName: "player") as? SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
func touchDown(atPoint pos: CGPoint) {
jump()
}
func jump() {
player?.texture = SKTexture(imageNamed: "player_jumping")
player?.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 500))
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
func touchUp(atPoint pos: CGPoint) {
player?.texture = SKTexture(imageNamed: "player_standing")
}
}
Run Code Online (Sandbox Code Playgroud)
在玩家的属性检查器窗口中,请确保仅选择"动态"和"受重力影响"选项,否则跳转后它不会回落到地面.:)
我不认为物理对于一个简单的游戏来说会有点过分,因为有人在之前的回答中说过......对于iPhone或iPad硬件而言,这并不是什么大不了的事,它们具有疯狂的计算能力.
对于这样的游戏来说,使用物理学是多余的。甚至 2D 马里奥游戏也不使用物理,所以我怀疑您是否需要它。
作为一个非常简单的实现,您可以使用 s 序列SKAction。
// move up 20
let jumpUpAction = SKAction.moveBy(x: 0, y: 20, duration: 0.2)
// move down 20
let jumpDownAction = SKAction.moveBy(x: 0, y: -20, duration: 0.2)
// sequence of move yup then down
let jumpSequence = SKAction.sequence([jumpUpAction, jumpDownAction])
// make player run sequence
player.run(jumpSequence)
Run Code Online (Sandbox Code Playgroud)
那应该有效。不过,我可能在浏览器中输入了错误的内容。
您可以调整它以使跳跃看起来更自然。也许在跳跃过程中添加更多步骤来改变随着时间的推移上升/下降的速度,使其看起来像是在加速。ETC...
| 归档时间: |
|
| 查看次数: |
4177 次 |
| 最近记录: |