Feeds:
Posts
Comments

Archive for January, 2008

Predictive Shooting

It has been quite a while since my last blog post. I have a lot of useful ideas that would make great posts but some super cool Electrotank projects have been sucking up my life.

One of our smaller projects is a tower defense game due out soon. For this game we developed a way to precisely answer this question: If a tower wants to fire off a bullet right now and hit a specific moving target, at what angle should it shoot?

The end result is a function that can find that angle for you. If you use it then you’ll get a direct hit every time! If that makes your AI too perfect, then tack on some random variation to the angle and it will be less precise the further away it is from the target.

The known information are these things:

  • Current position of the target
  • The target’s velocity (acceleration not supported here)
  • Position of the tower
  • Shot speed
  • Length of tower muzzle, if any

The equations of motion for the target are:

x1 = x1o + v1*cos(theta)*t
y1 = y1o + v1*sin(theta)*t

  • x1o – Current x position of target
  • y1o – Current y position of target
  • v1 – Speed of target
  • theta – Angular direction of target
  • t – Time variable

The equations of motion for the bullet are:

x2 = (x2o+n*cos(alpha)) + v2*cos(alpha)*t
y2 = (y20+n*sin(alpha)) + v2*sin(alpha)*t

  • y1o – Y position of tower
  • x2o – X position of tower
  • v2 – Bullet speed
  • alpha – The unknown angle to shoot
  • n – The length of the muzzle
  • t – Time variable

You can download the source code which contains the solution here:
Download source

click to view example

Advertisements

Read Full Post »