【发布时间】:2016-04-30 11:02:39
【问题描述】:
下面的代码是我在 pygame 中的射击游戏的子弹类。如您所见,如果您运行完整游戏 (https://github.com/hailfire006/economy_game/blob/master/shooter_game.py),只要玩家不移动,代码就可以很好地向光标发射子弹。但是,我最近添加了滚动,每次玩家接近边缘时,我都会更改全局 offsetx 和 offsety。然后使用这些偏移量在各自的绘图函数中绘制每个对象。
不幸的是,一旦玩家滚动并添加了偏移量,我在子弹的 init 函数中的子弹物理不再起作用。为什么偏移量会影响我的数学运算?如何更改代码以使子弹朝正确的方向发射?
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
self.name = "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):
make_bullet_trail(self,self.launch_point)
self.rect = pygame.Rect((self.x + offsetx,self.y + offsety),(self.width,self.height))
pygame.draw.rect(screen,(255,0,40),self.rect)
【问题讨论】: