Reputation: 591
I am trying to move a rectangle to a specific point with a specific speed.
however it only works properly if x,y
(the point i am trying to move it to) are the same. otherwise, if x
was bigger than y
it would move at a 45 degree angle until self.location[1]==y
(it reached where it needed to be for y
), then it would move in a straight for x
and vise versa.
i know that i would have to change speed_y
so that it was slower. how do i work out what speed i need y to be at in order to get the rectangle to move to location
in a straight line no matter what location
is?
full function:
def move(self,x,y,speed):
if speed==0:
self.location=[x,y]
else:
speed_x = speed
speed_y = speed
if x > 0 and not self.location[0]==x: # x is positive and not already where it needs to be
if not x == y:
speed_x = something # need to slow down the speed so that it gets to y as the same time as it gets to x
self.speed_x=speed_x
else: self.speed_x=0
if y > 0 and not self.location[1]==y: # same for y
if not x == y:
speed_y = something # need to slow down the speed so that it gets to y as the same time as it gets to x
self.speed_y=speed_y
else: self.speed_y=0
Upvotes: 0
Views: 619
Reputation: 26
You should set your speeds to a ratio of required distance for each axis. e.g. if distance to x is half distance to y then speed_x should be half speed_y.
Further example as requested:
distance_x = x-self.location[0]
distance_y = y-self.location[1]
if abs(distance_x) < abs(distance_y):
ratio = distance_x/abs(distance_y)
speed_x = ratio * speed
edit: Reworked the directions of example.
Upvotes: 1
Reputation: 11
I don't quite get what you are asking for, but see if this helps you:
speed_x = speed*(cos(atan2((y-self.location[1]), (x-self.location[0]))))
speed_y = speed*(sin(atan2((y-self.location[1]), (x-self.location[0]))))
That would "slow" the speed you are given by splitting it in the values needed to get to where you want your box to be at the same time.
Pardon any errors in my english/python, im not native on either one :)
Upvotes: 1
Reputation: 142631
You need mathematical calculations to get new position in every move.
Upvotes: -1