【问题标题】:Moving SKSpriteNode to direction of touch将 SKSpriteNode 移动到触摸方向
【发布时间】:2017-09-21 13:49:28
【问题描述】:

这里有游戏的打印屏幕:

我有一个静态的 SKSpriteNode(播放器),它正在旋转到触摸的方向。这是我的代码:

class GameplayScene: SKScene, SKPhysicsContactDelegate {

static let Pi = CGFloat(Double.pi)
static let DegreesToRadians = Pi / 180

override func touchesMoved(_ touches: Set<UITouch>, with event: 
UIEvent?) {
    let curTouch = touches.first! as UITouch
    let curPoint = curTouch.location(in: self)

    let deltaX = self.player.position.x - curPoint.x
    let deltaY = self.player.position.y - curPoint.y
    let angle = atan2(deltaY, deltaX)

    self.player.zRotation = angle + 90 * GameplayScene.DegreesToRadians
}
}

现在,我想每秒从与屏幕触摸方向相同的玩家身上发射子弹。当子弹移出屏幕时,我想实现“SKAction.removeFromParent”。

这是我的 fireMissile 函数:

func fireMissile() {
    let missile = SKSpriteNode(color: .yellow, size: CGSize(width: 20, 
    height: 5))
    missile.name = "Missile"
    missile.position = CGPoint(x: player.position.x + 30, y: 
    player.position.y)
    missile.zPosition = 2
    missile.physicsBody = SKPhysicsBody(rectangleOf: missile.size)
    missile.physicsBody?.isDynamic = false
    missile.physicsBody?.categoryBitMask = ColliderType.Bullet
    missile.physicsBody?.collisionBitMask = ColliderType.Enemy
    missile.physicsBody?.contactTestBitMask = ColliderType.Enemy

    self.addChild(missile)

}

【问题讨论】:

  • 我不是已经给你这个答案了吗?
  • 困惑,或者你在这里问两个不同的问题?你需要帮助移除子弹,还是帮助旋转坦克?或帮助移动坦克?这些都是单独的问题:)
  • Fluidify - 我想让子弹(从玩家)以恒定的速度朝屏幕上的触摸方向射击,基本上。抱歉,不清楚:P
  • 确保您使用@Name 以便我们收到通知 :) 我只是再次遇到这个问题...

标签: swift sprite-kit skaction


【解决方案1】:

对于计时器,您需要使用这个:

run(SKAction.repeatForever(SKAction.sequence([SKAction.run {
        yourFunction()
        }, SKAction.wait(forDuration: 1)])), withKey: "key")

至于导弹射击,按顺序添加SKActions。第一个应该把子弹放在你的玩家面前,第二个会移动导弹,第三个会删除,但由于顺序,这只会在其他行之后运行。如果您想稍后在动画中间停止它,请确保您有此序列的键。应该看起来像这样:

missile.zRotation = player.zRotation
missile.position = CGPoint(x:player.size.width/2*cos(player.zRotation)+player.position.x ,y:player.size.height*sin(player.zRotation)+player.position.y)
 missile.run(SKAction.sequence([SKAction.move(to: CGPoint(x:frame.size.width*cos(player.zRotation)+player.position.x ,y:frame.size.height*sin(player.zRotation)+player.position.y), duration: 0.5), SKAction.removeFromParent()]), withKey: "move")

【讨论】:

  • 最后的运行可能有轻微的语法错误,但你可以修复它
  • 你不想在 sprite kit 中使用Timer,你想通过动作使用内置的计时方法
  • 谢谢布鲁斯 - 是的,我在最后一行中确实遇到了语法问题,说“类型'([SKAction])-> SKAction'没有下标成员”。不,还没有解决:/
  • 使用这一行:missile.run(SKAction.sequence([SKAction.move(to: CGPoint(x:frame.size.widthcos(player.zRotation)+player.position. x ,y:frame.size.heightsin(player.zRotation)+player.position.y), duration: 0.5), SKAction.removeFromParent()]), withKey: "move") 是的,跟随 Knight's建议,因为他的方法可以更好地控制
  • 更新您的答案以使用 SKAction 而不是计时器,您将获得 +1 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多