Reputation: 35
I've defined a function which allows me to move an object diagonally:
if(myX > targetX):
dx = myX - targetX
else:
dx = targetX - myX
if(myY > targetY):
dy = myY - targetY
else:
dy = targetY - myY
if(dy == 0):
dy = 1
if(dx == 0):
dx = 1
#Calc Movement
if(dx < dy):
Speedy = dy/dx
Speedx = 1
if(dx > dy):
Speedy = 1
Speedx = dx/dy
elif(dx == dy):
Speedx = 1
Speedy = 1
if(myX < targetX):
Speedx = Speedx * -1
if(myY < targetY):
Speedy = Speedy * -1
return Speedx,Speedy
The code works, but the problem is that it doesn't do what I want. Right now the object speeds up if I move closer to it, which looks rather odd. I am very aware why it does this, but is there an easy way to fix the speed to be constant, but not the direction?
Upvotes: 0
Views: 1607
Reputation: 2216
If you do it this way dx and dy are scalars of a vector that points from your guy to the target. Then you divide by the magnitude of both of them, here it is represented as dz. Now dx and dy represent a unit vector. Once you multiply them by speed you will get your object moving at a constant speed, but varrying direction.
import math
#set speed to how fast you want your guy to move
speed = 1
dx = myX - targetX
dy = myY - targetY
dz = math.sqrt(dx**2 + dy**2)
speedx = dx/dz * speed
speedy = dy/dz * speed
Upvotes: 2