你好我使用这段代码让玩家精灵跟随鼠标的位置(左/右),但是当鼠标停在特定位置时,玩家跟随它然后开始从左到右振动 我认为问题出在更新功能的self.vel_x中。
class Player(pygame.sprite.Sprite):
#init Player Sprite
#sprite player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.image.load(os.path.join(image_folder,"Player.png"))
self.rect = self.image.get_rect()
self.vel_x = 0
self.speed = 30
self.friction = 3.5
self.rect.center = (420,360)
self.delta = clock.tick(FPS) / 1000.00
def update(self):
self.getX = pygame.mouse.get_pos()[0]-100 # get the X position of mouse
self.rect.x +=self.vel_x
##i think the problem is in here
self.vel_x = self.vel_x*(1-min(self.delta*self.friction,1))
#print "the GetX is ", self.getX
#print "the Rect.x is ", self.rect.x
if self.getX > self.rect.x:
self.vel_x+= self.speed*self.delta
else:
self.vel_x-= self.speed*self.delta
答案 0 :(得分:1)
这里的问题是你的速度步长。 self.speed*self.delta
大于1像素,这是鼠标光标消耗的空间。尝试检查播放器和光标之间的距离。如果该距离小于某个分辨率,则不要更新精灵的位置。
resolution = 5 # pixels
if abs(self.getX - self.rect.x) > resolution:
if self.getX > self.rect.x:
self.vel_x+= self.speed*self.delta
else:
self.vel_x-= self.speed*self.delta
else:
self.vel_x = 0