Skip to content
Advertisement

Python: Setting the X and Y vectors of a bullet

I need to calculate the vector_x and vector_y of a bullet, fired from x1, y1. The target is at x2, y2.

vector_x describes the number of units the bullet travels in the x direction per second. vector_y describes the same, just with the y direction.

I tried many different versions of the same function, but I was unable to come up with a version that:

  • Keeps vector_x and vector_y between 0 and 1
  • The bullets hit the target (assuming inaccuracy is 0), no matter where the target is.
  • Inaccuracy has the same hit chance no matter where the target is relative to x1, x1.

x 0, y 0 is at the top left corner.

This is my best attempt so far:

JavaScript

While this works in some cases, it mostly fires in wrong directions. How can I fix this code?

Advertisement

Answer

A simple unit vector approach:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement