子弹射击方向的子弹

时间:2017-01-07 18:29:42

标签: swift vector direction projectile

到目前为止,我的应用程序中间有一个大球,中间还有一个小球。我希望能够点击屏幕上的任何地方,小球向那个方向射击。我听说有人说过创建向量,但我似乎无法在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)

    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用操作动画SKSprideNode s:

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]];
}