Pygame墙在特定位置

时间:2019-12-03 15:35:50

标签: python pygame

如何在特定位置添加墙?我知道边界,但不知道具体位置。玩家必须从4个边缘与墙碰撞。

我正在使用Windows。

我的代码:

import pygame as P
import sys

P.init()
R = (700, 460)
W = P.display.set_mode(R)
FPS = P.time.Clock()

player_x = 0
player_y = 0
player_s = 5

Open = True
while Open:
    FPS.tick(60)
    for event in P.event.get():
        if event.type == P.QUIT:
            Open = False
    keys = P.key.get_pressed()
    if keys[P.K_UP]:
        player_y -= 1 * player_s
    if keys[P.K_LEFT]:
        player_x -= 1 * player_s
    if keys[P.K_DOWN]:
        player_y += 1 * player_s
    if keys[P.K_RIGHT]:
        player_x += 1 * player_s

    W.fill((134, 192, 108))
    P.draw.rect(W, (0, 0, 255), (player_x, player_y, 32, 32))
    P.display.update()

P.quit()

1 个答案:

答案 0 :(得分:0)

为防止玩家与墙壁碰撞(在这种情况下为矩形),您需要添加一些基本的碰撞检测功能。一种简单的方法是在每次按下键盘时检查播放器向所需方向移动是否会导致播放器位于墙壁内。检查冲突的函数的示例为:

def collides(player_x, player_y, wall_x, wall_y, wall_width, wall_height)
    """Returns True if player is inside the wall, otherwise False"""
    return wall_x < player_x < wall_x + wall_width and wall_y < player_y < wall_y + wall_height

然后,在检查玩家输入时,您需要将碰撞函数与墙的值相加。在示例中,我使用了(0,0)大小为32x32的假想壁

    ...
    if keys[pg.K_UP] and not collides(player_x, player_y - player_s, 0, 0, 32, 32):
        player_y -= 1 * player_s
    if keys[pg.K_LEFT] and not collides(player_x - player_s, player_y, 0, 0, 32, 32):
        player_x -= 1 * player_s
    if keys[pg.K_DOWN] and not collides(player_x, player_y + player_s, 0, 0, 32, 32):
        player_y += 1 * player_s
    if keys[pg.K_RIGHT] and not collides(player_x + player_s, player_y, 0, 0, 32, 32):
        player_x += 1 * player_s

    WINDOW.fill((134, 192, 108))

    # example wall at pos (0, 0) with width of 32 and height of 32
    pg.draw.rect(WINDOW, (0, 0, 255), (0, 0, 32, 32))
    pg.display.update()
    ...

注意:此示例是针对单个墙的,对于多个墙,您需要跟踪每堵墙并检查是否与每堵墙发生碰撞