et1337

Target lead code

Aug 30th, 2017
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. We have a target moving at a certain velocity. We want to hit it with a projectile that travels a certain speed.
  2.  
  3. To find where to aim, we need to find some point along a ray starting at the target's current position and continuing out in front of it in the direction of the target's velocity.
  4.  
  5. How far in front of the target we aim depends on how long it takes for the projectile to get there.
  6.  
  7. That means the intersection is described by this equation:
  8.  
  9. Vector3 intersection = target_pos + target_velocity * x;
  10.  
  11. Where x is how long the projectile takes to reach this point. We could estimate x by seeing how far away the target is right *now* and figuring out how long the projectile would take to travel that distance. But what we really need to know is how long the projectile would take to reach the intersection, not the target's current position.
  12.  
  13. We need another equation. Let's assume for a second that we know where the intersection point is. How long would it take a projectile starting at "projectile_start", traveling at "projectile_speed", to reach the intersection?
  14.  
  15. float x = (intersection - projectile_start).magnitude / projectile_speed;
  16.  
  17. Now let's substitute in "intersection" from the first equation.
  18.  
  19. float x = (target_pos + target_velocity * x - projectile_start).magnitude / projectile_speed;
  20.  
  21. The ".magnitude" operation is basically doing a dot product, and then taking a square root. If you write out the whole dot product and do some algebra rearrangement, you end up with this:
  22.  
  23. Vector3 to_target = target_pos - projectile_start;
  24. float x = Mathf.sqrt(Vector3.dot(to_target, to_target) / ((projectile_speed * projectile_speed) - 2.0f * Vector3.dot(to_target, target_velocity) - Vector3.dot(target_velocity, target_velocity)));
  25.  
  26. Plug x back into the first equation, and that's where you should aim.
Advertisement
Add Comment
Please, Sign In to add comment