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
x
27
27
1
def get_vectors(x1, y1, x2, y2, inaccuracy=0):
2
x2 += random.randint(inaccuracy * -1, inaccuracy)
3
y2 += random.randint(inaccuracy * -1, inaccuracy)
4
5
x_dist = x2 - x1
6
y_dist = y2 - y1
7
8
dist = [x_dist, y_dist]
9
10
11
if x_dist >= 0:
12
if y_dist >= 0: # BOTH POSITIVE
13
vector_x = x_dist / max(dist, key=abs)
14
vector_y = y_dist / max(dist, key=abs)
15
else: # X POSITIVE Y NEGATIVE
16
vector_x = x_dist / max(dist, key=abs) * -1
17
vector_y = y_dist / max(dist, key=abs) * -1
18
else:
19
if y_dist >= 0: # X NEGATIVE Y POSITIVE
20
vector_x = x_dist / max(dist, key=abs)
21
vector_y = y_dist / max(dist, key=abs)
22
else: # BOTH NEGATIVE
23
vector_x = x_dist / max(dist, key=abs) * -1
24
vector_y = y_dist / max(dist, key=abs) * -1
25
26
return vector_x, vector_y
27
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
1
18
18
1
def get_vector(x1, y1, x2, y2) -> tuple[int, int]:
2
3
# Vector v or difference
4
v_x = x2 - x1
5
v_y = y2 - y1
6
7
# TODO: Add inaccuracy to v
8
9
10
# lenght of v
11
v_len = (v_x**2 + v_y**2)**0.5
12
13
# unit vector u of v
14
u_x = v_x / v_len
15
u_y = v_y / v_len
16
17
return (u_x, u_y)
18