In each update, it is necessary to update the position
and zRotation
enemy.
Seeker and purpose
Ok, so add some nodes to the scene. We need a seeker and a goal. The seeker will be a rocket, and the target will be a touch. I said that you should do this inside the update method: but I will use the touchhesMoved method to make a better example. Here's how you should set up the scene:
import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { let missile = SKSpriteNode(imageNamed: "seeking_missile") let missileSpeed:CGFloat = 3.0 override func didMoveToView(view: SKView) { missile.position = CGPoint(x: frame.midX, y: frame.midY) addChild(missile) } }
Aiming
To realize the goal, you need to calculate how much you need to rotate the sprite based on your goal. In this example, I will use a rocket and point it to the place of contact. To accomplish this, you must use the atan2 function, like this (inside the touchesMoved:
method:
if let touch = touches.first { let location = touch.locationInNode(self) //Aim let dx = location.x - missile.position.x let dy = location.y - missile.position.y let angle = atan2(dy, dx) missile.zRotation = angle }
Note that atan2 takes parameters in y, x order, not x, y.
So, right now we have a corner in which the rocket should go. Now let's update its position based on this angle (add this method inside touchesMoved:
right under the aiming part):
//Seek let vx = cos(angle) * missileSpeed let vy = sin(angle) * missileSpeed missile.position.x += vx missile.position.y += vy
And that would be so. Here is the result:
Notice that in the Sprite-Kit, an angle of 0 radians indicates the positive x axis. And the positive angle is counterclockwise:
More details here .
This means that you must orient your walkie-talkie to the right. not up . You can also use an image with an upward orientation, but you will need to do something like this:
missile.zRotation = angle - CGFloat(M_PI_2)