I work with Xcode 6, SpriteKit and Swift,
I have a SKSpriteNode which is the default Spaceship image of a new Xcode project. This spaceship have a physicbody, but is not affected by the gravity, I want to simulate the space.
I want that when I tap the screen, a force is applied to the node so the spaceship can go forward. The problem is when the spaceship has rotated and I try to apply a force, the spaceship will not go forward like I want, but in the direction of the force applied, which is normal.
I want to know if there is any way to apply a force to a node according to its zRotation ? So no matter in which direction will be the spaceship, it will always go forward.
I can't give it a try right now, but it should work :
// grab the spaceship rotation and add M_PI_2
var spaceShipRotation : CGFloat = spaceShipNode.zRotation
var calcRotation : Float = Float(spaceShipRotation) + Float(M_PI_2);
// cosf and sinf use a Float and return a Float
// however CGVector need CGFloat
let intensity : CGFloat = 10.0 // put your value
let xv = intensity * CGFloat(cosf(calcRotation))
let yv = intensity * CGFloat(sinf(calcRotation))
let vector : CGVector = CGVectorMake(xv, yv)
// apply force to spaceship
spaceShipNode.physicsBody?.applyForce(vector)
You have to work with math, or more precisely with trigonometry, which includes : PI, cos, sin, ... I'm not really confortable with all of that, especially without being to try right now, but as I've told it should work. Let me know !
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments