2

I'm trying my best to make a simple "tower-defense" game on my own (both to learn SpriteKit and get my feet wet in game development in general).

I've got most of the game working, but my trouble is when it comes to the tower "shooting" at the enemies that walk across the screen.

I'm not quite sure how to go about moving the tower "bullets" to the enemy. The enemy itself moves statically, point to point, until it hits an endpoint where it dies.

However, the bullet needs to dynamically shift it's "path" so I can't use the moveTo(x: , y:) method to move it, or it looks silly (the bullet will move in a straight line to where the enemy was upon the bullet's initialization).

I'm not sure if what I need to do is implement paths (i.e. CGPath's) because frankly, I can't quite get a grasp of what a CGPath is. So here I'm kind of stuck as to the direction to go in.

Is there a simple function that will allow a sprite to move or 'follow' another sprite? (In which case when they collide I can simply delete the bullet).

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Su_toL
  • 167
  • 2
  • 15

1 Answers1

1

For every update cycle, calculate a vector from the bullet to the enemy's position. Normalise this to a length of 1. Then move the bullet via an SKAction to the end of the this vector. You'l have to do some calculations with the distance to move and the bullet's speed to work out how long the SKAction should take. You could use an SKConstraint to rotate the bullet to face the enemy automatically.

This links will help with the vector stuff but Ill try and post some code later:

https://www.raywenderlich.com/90520/trigonometry-games-sprite-kit-swift-tutorial-part-1

Steve Ives
  • 7,894
  • 3
  • 24
  • 55
  • You might also be able to do it with a distance constraint that continuously decreases... – Steve Ives Apr 15 '16 at 09:23
  • 1
    You also can create a distance constraint for the following behaviour: http://developerplayground.net/how-to-implement…and-swift-part-2/ – Stefan Apr 15 '16 at 20:37