如何阻止角色在碰撞后移动?

2024-09-29 17:16:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python创建我自己的游戏,我试图让我的角色在与墙相撞时不移动。在

我试过让角色的x速度和y速度为0,但这似乎不起作用。我见过有人用面向对象编程来做这件事,有没有办法不使用OOP呢?在

# character co-ordinates
gokuX = 0
gokuY = 0

# using arrow keys to move the character
if keys[pygame.K_LEFT]:
    gokuVx = -RUN_SPEED
elif keys[pygame.K_RIGHT]:
    gokuVx = RUN_SPEED
if keys[pygame.K_UP]:
    gokuVy = -RUN_SPEED
elif keys[pygame.K_DOWN]:
    gokuVy = RUN_SPEED

# the rectangle around my character
gokuRect = pygame.Rect(gokuX, gokuY, gokuW, gokuH)

# store the rectangles inside a list
lvl1rlist = [lvl1r0, lvl1r1, lvl1r2, lvl1r3, lvl1r4, lvl1r5, lvl1r6, 
lvl1r7, lvl1r8]

# detecting collisions between the character and the rectangles
for i in range(9):
    if gokuRect.colliderect(lvl1rlist[i]):
        # I don't know what to do here to make the character not move

我希望我的角色不能越过墙,但仍然可以自由移动时,不与他们碰撞


Tags: thetorun角色moveifkeyspygame
1条回答
网友
1楼 · 发布于 2024-09-29 17:16:49

基于你的部分代码,我假设你需要重新安排你的功能-你只想在没有冲突的情况下“移动”你的字符矩形-所以碰撞测试需要在你移动之前或者之后进行(在这种情况下,你需要反转之前的移动-见备选方案2)。在

备选方案1:

逻辑:检查是否有冲突;如果上次移动后没有冲突,则移动角色。在

    collision_detected = False

    # detecting collisions between the character and the rectangles after the last movement (!)
    for i in range(9):
        if gokuRect.colliderect(lvl1rlist[i]):
            print("collision detected.")       
            collision_detected  = True
            RUN_SPEED = 0
            # Show "Game Over" Screen



     if not collision_detected: 
        if keys[pygame.K_LEFT]:
            gokuVx = -RUN_SPEED
        elif keys[pygame.K_RIGHT]:
            gokuVx = RUN_SPEED
        if keys[pygame.K_UP]:
            gokuVy = -RUN_SPEED
        elif keys[pygame.K_DOWN]:
            gokuVy = RUN_SPEED     


    # the rectangle around my character
    gokuRect = pygame.Rect(gokuX, gokuY, gokuW, gokuH)

备选方案2:(反向移动-使角色不在墙上,而是停在墙前面)

逻辑上:移动角色;检查是否有冲突;如果有冲突,则反转上一个移动并显示“游戏结束”屏幕

^{pr2}$

相关问题 更多 >

    热门问题