我需要在图像周围添加矩形边框,以使角色不再走动。如果我的角色停在某个坐标而不是在图像上走动,那就太好了。
我尝试用'x'和'y'坐标创建边框,但是边框似乎在屏幕上延伸。
import pygame
from pygame.locals import *
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 700
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT,))
pygame.display.set_caption("Zombie Hunters")
background = pygame.image.load("background.jpg").convert()
background = pygame.transform.scale(background, (SCREEN_WIDTH,SCREEN_HEIGHT))
player = pygame.image.load("character no gun.png").convert_alpha()
player = pygame.transform.scale(player, (270, 270))
# these are the coordinates to move the player
x, y = 0, 0
MOVE_RIGHT = 1
MOVE_LEFT = 2
MOVE_UP = 3
MOVE_DOWN = 4
direction = 0
speed = 1
#House barrier
barrier_xlocation = 345
barrier_ylocation = 80
barrier_width = 190
barrier_height = 260
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == ord('q'):
pygame.quit()
exit()
if event.key == K_LEFT:
direction = MOVE_LEFT
if event.key == K_RIGHT:
direction = MOVE_RIGHT
if event.key == K_UP:
direction = MOVE_UP
if event.key == K_DOWN:
direction = MOVE_DOWN
elif event.type == KEYUP:
if event.key == K_LEFT:
direction = 0
if event.key == K_RIGHT:
direction = 0
if event.key == K_UP:
direction = 0
if event.key == K_DOWN:
direction = 0
if(direction == MOVE_LEFT):
x-= speed
if(direction == MOVE_RIGHT):
x+= speed
if(direction == MOVE_UP):
y-= speed
if(direction == MOVE_DOWN):
y += speed
#Background
screen.blit(background, (0, 0))
#House border
pygame.draw.rect(screen, (255,0,0), (barrier_xlocation,barrier_ylocation,barrier_width,barrier_height), 2)
#Player hitbox
pygame.draw.rect(screen, (255,0,0), (x + 117,y + 105, 50,50),2)
screen.blit(player, (x,y))
pygame.display.update()
我没有收到任何错误消息,但需要在房屋周围创建边框。
答案 0 :(得分:2)
使用pygame.Rect
对象和.colliderect()
检查两个矩形的冲突。
存储播放器的当前位置。玩家位置改变后,检查与障碍物的碰撞。当播放器和障碍物发生碰撞时,请重置播放器的位置。
[pygame.Surface
对象的大小可以通过.get_size()
获得:
# store current position
px, py = x, y
# change position
if(direction == MOVE_LEFT):
x-= speed
if(direction == MOVE_RIGHT):
x+= speed
if(direction == MOVE_UP):
y-= speed
if(direction == MOVE_DOWN):
y += speed
# set player and barrier rectangle
playerRect = pygame.Rect(x, y, *player.get_size())
barrierRect = pygame.Rect(
barrier_xlocation, barrier_ylocation, barrier_width, barrier_height)
# check for collision
if playerRect.colliderect(barrierRect):
# reset position
x, y = px, py