子弹按攻丝方向发射

Bullet Firing In Direction Of Tap

到目前为止,我的应用程序中间有一个大球,中间也有一个小球。我希望能够点击屏幕上的任意位置,然后小球会朝那个方向射击。我听说有人说要创建向量,但我似乎无法在 swift 中使用它们 3. 我是初学者,很抱歉提出一个愚蠢的问题!

这是我的代码:

var mainBall = SKSpriteNode(imageNamed: "Ball")

override func didMove(to view: SKView) {


    mainBall.size = CGSize(width: 300, height: 300)
    mainBall.position = CGPoint(x: frame.width / 2, y: frame.height / 2)

    self.addChild(mainBall)

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    if let touch = touches.first {
        let position = touch.location(in: self)
        print(position.x)
        print(position.y)
    }

    for touch in (touches) {
        touch.location(in: self)

        let smallBall = SKSpriteNode(imageNamed: "Ball")
        smallBall.position = mainBall.position
        smallBall.size = CGSize(width: 100, height: 100)
        smallBall.physicsBody = SKPhysicsBody(circleOfRadius: smallBall.size.width / 2)
        smallBall.physicsBody?.affectedByGravity = false

        self.addChild(smallBall)

    }
}

您可以使用动作为 SKSprideNodes:

设置动画
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else {
        return        
    }

    let newPosition = touch.location(in: self)
    ...
    //assuming self.smallBall exists and is visible already:
    [self.smallBall runAction:[SKAction moveTo:newPosition duration:1.0]];
}