Skip to content
Advertisement

How do you shoot a bullet towards mouse in pygame at a constant speed?

I am trying to shoot a bullet towards my mouse in pygame, here is my code:

JavaScript

I am confused on how to make this work, I think somehow I am rounding something, but even after I put float() in, it still is not working. Also, before when I used the mouse coordinates, it works, but when close to tank, it shoots slow, and insanely fast farther from the tank. Somebody please help, thanks!

Advertisement

Answer

Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. […]

The fraction part of the coordinates gets lost when the new position of the object is assigned to the Rect object.
You have to do it the other way around. Change self.x_loc and self.y_loc, but update self.bullet_rect.center:

JavaScript

See also these questions: Shooting a bullet in pygame in the direction of mouse and How can you rotate the sprite and shoot the bullets towards the mouse position.

Advertisement