如果物体与pygame中的墙壁碰撞,如何使物体停止移动?

问题描述

我正在制作一个涉及运动的迷你游戏。我创建了一个根据控件移动的对象,但是如果它与墙碰撞,如何使它不移动?

#Imports
import pygame,sys


#Functions




#General Set Up
pygame.init()
clock = pygame.time.Clock()

#Main Window

swid = 1280        
shgt = 700
screen = pygame.display.set_mode((swid,shgt))
pygame.display.set_caption("Raid: The Game || Movement Test")


#Game Rectangles

player = pygame.Rect(30,30,30)
wall = pygame.Rect(140,80,1000,20)
window = pygame.Rect(300,400,220,20)
door = pygame.Rect(500,500,120,18)

bgcol = (0,0)
playercol = (200,0)
wallcol = pygame.Color("grey12")
doorcol = pygame.Color("blue")
windowcol = (100,100,100)

xwalkspeed = 0
ywalkspeed = 0


while True:
    #Handling Input
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                ywalkspeed += 10
            if event.key == pygame.K_UP:
                ywalkspeed -= 10
            if event.key == pygame.K_LEFT:
                xwalkspeed -= 10
            if event.key == pygame.K_RIGHT:
                xwalkspeed += 10

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_DOWN:
                ywalkspeed -= 10
            if event.key == pygame.K_UP:
                ywalkspeed += 10
            if event.key == pygame.K_LEFT:
                xwalkspeed += 10
            if event.key == pygame.K_RIGHT:
                xwalkspeed -= 10
    
    
    
    player.x += xwalkspeed
    player.y += ywalkspeed

    distancebetween = 0

    if player.colliderect(wall):
        ywalkspeed = 0
        xwalkspeed= 0
                       

    if player.top <= 0:
        player.top = 0
    
    if player.bottom >= shgt:
        player.bottom = shgt

    if player.left <= 0:
        player.left = 0

    if player.right >= swid:
        player.right = swid


    
    #Visuals
    screen.fill(bgcol)
    pygame.draw.ellipse(screen,playercol,player)
    pygame.draw.rect(screen,wallcol,wall)
    pygame.draw.rect(screen,doorcol,door)
    pygame.draw.rect(screen,windowcol,window)


    #Updating the Window
    pygame.display.flip()
    clock.tick(60)

只要我的对象碰撞到墙上,它就会开始向相反方向移动,直到在屏幕上不再可见。

我找到了它撞墙时为什么保持相反方向运动的原因。这是因为如果我朝墙壁移动,我的ywalkspeed = 10碰到墙壁,它变成0,那么如果我开始放开移动键,则ywalkspeed变成{{1 }}。我目前还不知道如何解决此问题,因为我只是菜鸟。

解决方法

使用copy()复制原始播放器矩形。移动播放器。如果检测到冲突,请还原播放器矩形:

copy_of_player_rect = player.copy()

# move player
# [...]

if player.colliderect(wall):
    player = copy_of_player_rect 
,

您可以观察墙壁与播放器之间的距离,并且当根据轴位置的距离为零时,只需执行

xwalkspeed = 0
ywalkspeed = 0

要测量距离和平滑逼真的运动,还可以使用Physics中的运动方程。