Skip to content Skip to sidebar Skip to footer

Finding Change In X And Y Given Two Points And Length Of Vector

I have a bullet shot from the first point(the player location), and it needs to travel towards the second point(the mouse click), at a given speed. Right now I have all this code.

Solution 1:

I hope I didn't make mistake - I don't remeber it too well.

EDIT: there was mistake in atan2(dy, dx) - has to be atan2(dx, dy)


It calculate new position (after one frame/move) if you have bullet's position and speed, and target's position.

You have to repeat it

import math

speed = 10

# bullet current position
x1 = 0
y1 = 0

# taget possition
x2 = 100
y2 = 100

dx = x2 - x1
dy = y2 - y1

angle = math.atan2(dx, dy)
#print(math.degrees(angle))

cx = speed * math.sin(angle)
cy = speed * math.cos(angle)
#print(cx, cy)# bullet new current position
x1 += cx
y1 += cy

print(x1, y1)

EDIT: Example with loop

EDIT: It needs abs() in if abs(cx) < abs(dx) or abs(cy) < abs(dy):

BTW: if target doesn't change place or bullet doesn't change angle then you can calculate cx,cy only once.

import math

defmove(x1, y1, x2, y2, speed):

    # distance
    dx = x2 - x1
    dy = y2 - y1

    # angle
    angle = math.atan2(dx, dy)
    #print(math.degrees(angle))# 
    cx = speed * math.sin(angle)
    cy = speed * math.cos(angle)
    #print(cx, cy)# if distance is smaller then `cx/cy`# then you have to stop in target.ifabs(cx) < abs(dx) orabs(cy) < abs(dy):
        # move bullet to new position
        x1 += cx
        y1 += cy
        in_target = Falseelse:
        # move bullet to target
        x1 = x2
        y1 = y2
        in_target = Truereturn x1, y1, in_target

#--- 

speed = 10# bullet position
x1 = 10
y1 = 0# taget possition
x2 = 120
y2 = 10print('x: {:6.02f} | y: {:6.02f}'.format(x1, y1))

in_target = Falsewhilenot in_target:
    x1, y1, in_target = move(x1, y1, x2, y2, speed)
    print('x: {:6.02f} | y: {:6.02f}'.format(x1, y1))

Result

x:10.00|y:0.00x:19.96|y:0.91x:29.92|y:1.81x:39.88|y:2.72x:49.84|y:3.62x:59.79|y:4.53x:69.75|y:5.43x:79.71|y:6.34x:89.67|y:7.24x:99.63|y:8.15x:109.59|y:9.05x:119.55|y:9.96x:120.00|y:10.00

BTW: if target doesn't change place or bullet doesn't change angle then you can calculate cx,cy only once.

Post a Comment for "Finding Change In X And Y Given Two Points And Length Of Vector"