2

I have this code which applies force to the bullet node and make it move towards the enemy. This case the rocket is always faces upwards. My question is how can i rotate this bullet to face to the direction where the node is head.

  let asd=SKSpriteNode(imageNamed: "nuke")
    asd.zPosition=3
    asd.setScale(0.1)
    asd.position=CGPoint(x: self.size.width*0.945, y: self.size.height*0.48)

   asd.physicsBody=SKPhysicsBody(rectangleOf: asd.size)
    asd.physicsBody?.affectedByGravity=true
    asd.physicsBody?.isDynamic=true

    self.addChild(asd)
    let scale=SKAction.scale(to: 0.4, duration: 0.5)

    asd.physicsBody?.applyForce(CGVector(dx: -63, dy: 130))
    let wait=SKAction.wait(forDuration: 10)
    let rem=SKAction.removeFromParent()
    let seq=SKAction.sequence([scale,wait,rem])
    asd.run(seq)
}
sure01
  • 19
  • 1
  • 3
  • Possible duplicate of https://stackoverflow.com/questions/31421912/rotate-an-object-in-its-direction-of-motion – 0x141E Mar 03 '18 at 04:19

2 Answers2

1

The rotation is the zRotation property.

self.zRotation = <angle>

You must first figure out the angle to set it to with some basic trig.

Angle is specified in radians and rotates counter clockwise so...

bullet 12 o'clock = 0
bullet  9 o'clock = pi/2
bullet  6 o'clock = pi
bullet  3 o'clock = pi * 3 / 2
Dennis
  • 555
  • 8
  • 17
  • The problem is that the angle is changing over time. The bullet's path is like a parabola. How can i achieve changing angle over time? – sure01 Mar 02 '18 at 17:03
  • In your update method calculate the angle based on the desired direction and apply zRotation each step. Or maybe not every step if that's too often but you could do it like every certain number of frames or something. – Dennis Mar 02 '18 at 17:51
  • I managed to apply movement restrictions through your sight. Thank you @Dennis – Vetuka Jan 08 '19 at 19:11
0

Get the velocity property (the speed vector) and compute an angle from it, then associate this angle to the zRotation property. Something like:

func didSimulatePhysics() {
  if let pb = bullet.physicsBody {
    bullet.zRotation = atan2(pb.velocity.dy, pb.velocity.dx)
}

provided bullet refers to the bullet in action...

Note: I used didSimulatePhysics to ensure that all physics computation have been made, so that the velocity vector is correct.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69