Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What you're asking is non-trivial. I'll start with the simplest solution and expand on that.</p> <p>First, assume that both you and your enemy are stationary. You need to compute the angle between you and your enemy, rotate your weapon to point at the enemy, and then fire. Use your favorite search engine to find a description of how to find the angle between two points on a plane (you did say 2D).</p> <p>Once you write code that can do the above, move on to:</p> <p>Your enemy is moving in a constant direction at a constant velocity. You are still stationary. This is a surprisingly difficult problem. To simplify, we'll assume that you can aim your weapon instantaneously.</p> <p>If you know where you and the enemy are, and the speed and direction of the enemy, then you can determine the enemy's position (and, consequently, his distance and direction from you) at any time.</p> <p>You know how fast your projectile can travel. So if you draw a line from your current position to intercept any position on the enemy's expected path of travel, you can determine how long it will take your projectile to hit the enemy. The key, then, is to find the point on the enemy's path that, were you to fire the projectile immediately, it would intersect the enemy at the proper time. This typically requires successive approximations.</p> <p>If you can't rotate your weapon instantaneously, then the problem becomes more difficult because the time it takes to rotate your weapon to point at the enemy depends on how fast and in what direction the enemy is traveling. More approximations are required.</p> <p>Things get even more involved when you and the enemy are both moving, although it's possible to construct the math so that you "hold yourself still". That is, do a transformation on the enemy's velocity and trajectory to reflect how the enemy is moving in relation to you. The math then becomes identical to the case of you being stationary.</p> <p>The math itself is at most elementary trigonometry. You need to know how to compute the distance between two points, the distance between a line and a point, the angle between two points, compute points on a line given a starting point and direction, and how to rotate about an arbitrary point. All of those are well-known problems that have many good examples online. You'll have to do a little research to find them, though.</p> <p>Probably your best bet is to find a good computer graphics tutorial.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload