Dan*_*Doe 5 python pygame rect
我本质上是想用 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
Run Code Online (Sandbox Code Playgroud)
这样做的问题是,玩家被“卡”在塔楼矩形内,尽管返回到碰撞开始之前所在的位置,但玩家矩形将始终被拉回到塔楼中,并且碰撞将继续进行。扳机。最初接触塔矩形后,玩家将无法向任何方向移动。
我在我的 pygame 游戏中做了同样的事情。您想要做的是创建一个所有对象都会使用的移动功能。它使得不可能遍历称为“一切”的渲染更新组中的任何精灵。如果精灵不是一切的一部分,它就不会发生碰撞。这是函数。这会产生一定程度的碰撞阻力。基本上,当推动一个物体时,它会向后推一定的量。任何不调用 move 函数的物体即使被推也不会移动,所以只有本来可以移动的物体才能被推,而像墙这样的东西在推时不会在板上滑动。
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
Run Code Online (Sandbox Code Playgroud)
它有很多代码,您可能想根据自己的目的更改它,但这是一个很好的方法。如果您想消除反弹功能,您可以考虑将朝向物体的任何移动设置为零,并仅允许远离物体的移动。然而,我发现反弹功能对我的游戏很有用并且更准确。
| 归档时间: |
|
| 查看次数: |
4699 次 |
| 最近记录: |