问题
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