我本质上是想用 pygame 制作一个“实体”对象。目标是在玩家接触时击退玩家。我目前使用的(但不能正常工作)如下:
keys_pressed = pygame.key.get_pressed()
if 1 in keys_pressed:
if keys_pressed[K_w]:
self.player_l[1] += -2
if self.player_r.colliderect(self.tower_r): self.player_l[1] -= -2
if keys_pressed[K_a]:
self.player_l[0] += -2
if self.player_r.colliderect(self.tower_r): self.player_l[0] -= -2
if keys_pressed[K_s]:
self.player_l[1] += 2
if self.player_r.colliderect(self.tower_r): self.player_l[1] -= 2
if keys_pressed[K_d]:
self.player_l[0] += 2
if self.player_r.colliderect(self.tower_r): self.player_l[0] -= 2
这个问题是玩家会“卡在”塔内会继续触发。在最初接触塔 Rect 后,玩家将无法向任何方向移动。
请您参考如下方法:
我在我的 pygame 游戏中做过同样的事情。您要做的是创建一个所有对象都将使用的移动函数。它使得不可能遍历名为 everything 的渲染更新组中的任何 Sprite 。如果一个 Sprite 不是一切的一部分,它就不会发生碰撞。这是功能。这会产生一定量的碰撞阻力。基本上,在插入一个物体时,它会向后推一定量。任何不调用移动函数的物体即使被推上去也不会移动,所以只有那些本来可以移动的物体才能被推,而像墙这样的东西在你推的时候不会滑过棋盘。
def moveRelative(self,other,speed): #This function is a function the one you need uses, which you may find useful. It is designed to move towards or a way from another sprite. Other is the other sprite, speed is an integer, where a negative value specifies moving away from the sprite, which is how many pixels it will move away from the target. This returns coordinates for the move_ip function to move to or away from the sprite, as a tuple
dx = other.rect.x - self.rect.x
dy = other.rect.y - self.rect.y
if abs(dx) > abs(dy):
# other is farther away in x than in y
if dx > 0:
return (+speed,0)
else:
return (-speed,0)
else:
if dy > 0:
return (0,+speed)
else:
return (0,-speed)
def move(self,dx,dy):
screen.fill((COLOR),self.rect) #covers over the sprite's rectangle with the background color, a constant in the program
collisions = pygame.sprite.spritecollide(self, everything, False)
for other in collisions:
if other != self:
(awayDx,awayDy) = self.moveRelative(other,-1) #moves away from the object it is colliding with
dx = dx + 9*(awayDx) #the number 9 here represents the object's resistance. When you push on an object, it will push with a force of nine back. If you make it too low, players can walk right through other objects. If you make it too high, players will bounce back from other objects violently upon contact. In this, if a player moves in a direction faster than a speed of nine, they will push through the other object (or simply push the other object back if they are also in motion)
dy = dy + 9*(awayDy)
self.rect.move_ip(dx,dy) #this finally implements the movement, with the new calculations being used
它有很多代码,您可能想根据自己的目的更改它,但这是一个很好的方法。如果你想消除反弹功能,你可以考虑将任何朝向对象的移动设置为零,并只允许远离它的移动。不过,我发现反弹功能对我的游戏很有用且更准确。
