I'm writing a little pirate game in Pygame. If you played sea battles in Empires Total War, you have an idea of what I would like to achieve:
The ship's sprite is at position (x1|y1)
. The player now clicks at position (x2|y2)
on the screen. The sprite is now supposed to take (x2|y2)
as its new position - by going there step by step, not by beaming there instantly.
I figured out that it has something to do with the diagonal of the rectangle (x1|y1)
,(x1|y2)
,(x2|y2)
,(x2|y1)
but I just can't figure it out, especially not with keeping the speed the same no matter what angle that diagonal has and considering that the x
and y
values of either (ship or click) might be bigger or smaller than the respective other.
This little snippet is my last try to write a working function:
def update(self, new_x, new_y, speed, screen, clicked):
if clicked:
self.xshift = (self.x - new_x)
self.yshift = ((self.y - new_y) / (self.x - new_x))
if self.x > (new_x + 10):
self.x -= 1
self.y -= self.yshift
elif self.x > new_x and self.x < (new_x + 10):
self.x -= 1
self.y -= self.yshift
elif self.x < (new_x - 10):
self.x += 1
self.y += self.yshift
elif self.x < new_x and self.x < (new_x - 10):
self.x += 1
self.y += self.yshift
else:
self.x += 0
self.y += 0
screen.set_at((self.x, self.y), (255, 0, 255))
The "ship" is just a pink pixel here. The reaction it shows upon my clicks onto the screen is to move roughly towards my click but to stop at a seemingly random distance of the point I clicked.
The variables are:
new_x
, new_y
= position of mouseclick
speed
= constant speed depending on ship types
clicked
= set true
by the MOUSEBUTTONDOWN
event, to ensure that the xshift and yshift of self are only defined when the player clicked and not each frame again.
How can I make the ship move smoothly from its current position to the point the player clicked?