user3150635 user3150635 - 1 year ago 116
Python Question

pygame bullet physics messed up by scrolling

the code below is the bullet class for my shooter game in pygame. as you can see if you run the full game ( the code works great to fire bullets at the cursor as long as the player isn't moving. However, I recently added scrolling, where I change a global offsetx and offsety every time the player gets close to an edge. These offsets are then used to draw each object in their respective draw functions.

unfortunately, my bullet physics in the bullet's init function no longer work as soon as the player scrolls and the offsets are added. Why are the offsets messing up my math and how can I change the code to get the bullets to fire in the right direction?

class Bullet:
def __init__(self,mouse,player):
self.exists = True
centerx = (player.x + player.width/2)
centery = (player.y + player.height/2)
self.x = centerx
self.y = centery
self.launch_point = (self.x,self.y)
self.width = 20
self.height = 20 = "bullet"
self.speed = 5
self.rect = None
self.mouse = mouse
self.dx,self.dy = self.mouse

distance = [self.dx - self.x, self.dy - self.y]
norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
direction = [distance[0] / norm, distance[1] / norm]
self.bullet_vector = [direction[0] * self.speed, direction[1] * self.speed]

def move(self):
self.x += self.bullet_vector[0]
self.y += self.bullet_vector[1]

def draw(self):
self.rect = pygame.Rect((self.x + offsetx,self.y + offsety),(self.width,self.height))

Answer Source

You don't take the offset into account when calculating the angle between the player and the mouse. You can fix this by changing the distance like this:

distance = [self.dx - self.x - offsetx, self.dy - self.y - offsety]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download