2

I found the this answer on Stack overflow, but I want to make a modification to it that I just can't figure out. The answer to that question shows how to make the missile move in the direction of your finger. However, I want it to move in the direction of another node (in my case a ship) Meaning that instead of following my finger, it follows the ship. How can a achieve this?

Thanks very much

Community
  • 1
  • 1
Harrison R
  • 67
  • 1
  • 8

1 Answers1

2

It is very simple:

1) Instead of touchesMoved use update method.

2) Instead of touch location use player's position.

override func update(currentTime: NSTimeInterval) {

        let location = player.position

        //Aim
        let dx = location.x - missile.position.x
        let dy = location.y - missile.position.y
        let angle = atan2(dy, dx)

        missile.zRotation = angle

        //Seek
        let vx = cos(angle) * missileSpeed
        let vy = sin(angle) * missileSpeed

        missile.position.x += vx
        missile.position.y += vy
}
Whirlwind
  • 14,286
  • 11
  • 68
  • 157
  • Thanks for the great answer. It works great, but the is one issue. When the two nodes collide, the missile's zPosition is all over the place, meaning that it starts to rotate like crazy. How can I fix this? – Harrison R Apr 18 '16 at 20:24
  • I've tried just creating an if else stamens saying that if they touched the zPosition would change, but that didn't work – Harrison R Apr 18 '16 at 20:33
  • @HarrisonR Well what will happen when contact occurs between player and a missile depends on you... You have to implement contact detection and take appropriate actions (remove nodes, make an explosion, etc). This was just an example of how to implement seeking / aiming logic. Anything beyond that is out of scope of the linked question, as well as out of scope of this question. – Whirlwind Apr 18 '16 at 21:01
  • I understand that, But I want it to just stop rotating when they touch. How can I do that? – Harrison R Apr 19 '16 at 00:21