I'm trying to create a game that when the player clicks, the player shoots a projectile on the same path of the point clicked. My code works fine so far, except that the farther away the player clicks, the faster it moves. Here is the code:
class Projectile(pygame.sprite.Sprite):
x2 = 0
y2 = 0
slope_x = 0
slope_y = 0
attack_location = ()
slope = 0
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.rect.x = 390
self.rect.y = 289
self.attack_location = (mouse_x,mouse_y)
self.mask = pygame.mask.from_surface(self.image)
self.x2 = self.attack_location[0]
self.y2 = self.attack_location[1]
self.slope_y = self.y2 - 300
self.slope_x = self.x2 - 400
def update(self):
self.rect.x += (self.slope_x) / 15
self.rect.y += (self.slope_y) / 15
My code is a bit sloppy and simple, but I'd like to know if there's a way to set the speed constant or maybe even use trigonometry for the movement of the projectile on an angle.
Actually, I have managed to normalize the vector, but the projectile comes out as if it is from (0,0), but the character's position is (400,300). I'm wondering if there's any way to make it so the vector starts at (400,300), or if there's another solution to my original problem. Thanks! Here is the code:
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
self.attack_location = (mouse_x,mouse_y)
self.mask = pygame.mask.from_surface(self.image)
self.x2 = self.attack_location[0]
self.y2 = self.attack_location[1]
self.d = math.sqrt(((self.x2)**2) + ((self.y2)**2))
self.slope_x = self.x2 / self.d
self.slope_y = self.y2 / self.d
def update(self):
self.rect.x += (self.slope_x) * 10
self.rect.y += (self.slope_y) * 10
You have to normalize the direction vector. Something like this:
d = math.sqrt(mouse_x * mouse_x + mouse_y * mouse_y)
self.slope_x = mouse_x / d - 300
self.slope_y = mouse_y / d - 400