Shoot bullet in the Direction the Ship is Facing Swift and Sprite Kit

喜你入骨 提交于 2019-12-06 15:07:36

问题


I am making a space shooter game, and I would like the ship to be able to fire bullets in the direction it is facing. I have figured out how to make the bullet rotate in the direction of the ship, but I haven't gotten it to shoot in the right direction. At the moment, I only shoot up. I have a screen shot down below. How can I fix this? Here is my code:

if shootButton.containsPoint(location) {

            let Bullet = SKSpriteNode(imageNamed: "BulletGalaga.png")
            Bullet.zPosition = -5

            Bullet.position = CGPointMake(ship.position.x, ship.position.y)
            Bullet.zRotation = ship.zRotation
            Bullet.zPosition = ship.zPosition

            let action = SKAction.moveToY(self.size.height + 30, duration: 0.8)
            //let action = SKAction.moveTo(self.ship.size.height, duration: 0.8)
            let actionDone = SKAction.removeFromParent()
            Bullet.runAction(SKAction.sequence([action, actionDone]))

            Bullet.physicsBody = SKPhysicsBody(rectangleOfSize: Bullet.size)
            Bullet.physicsBody?.affectedByGravity = false
            Bullet.physicsBody?.dynamic = false
            self.addChild(Bullet)

        }

Thanks.

Screenshot


回答1:


You are setting the zPosition? you mean zRotation. and that will only calculate the angle that the bullet draws, you need to do some trig to figure out where the bullet will go to in a straight line:

PSEUDO CODE:

let action = SKAction.moveTo(
               CGPointMake(
                            travelDistance * cos(Bullet.zRotation) + Bullet.position.x,
                            travelDistance * sin(Bullet.zRotation) + Bullet.position.y
               ), 
               duration: 0.8)



回答2:


let action = SKAction.moveTo(
                CGPointMake(
                    400 * -cos(Bullet.zRotation - 1.57079633) + Bullet.position.x,
                    400 * -sin(Bullet.zRotation - 1.57079633) + Bullet.position.y
                ),
                duration: 0.8)


来源:https://stackoverflow.com/questions/35784784/shoot-bullet-in-the-direction-the-ship-is-facing-swift-and-sprite-kit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!