我很难让碰撞100%正常工作。如果我一次只按一个键,碰撞似乎可以正常工作,但如果我按一个键并继续按,同时碰撞,然后按另一个键,碰撞似乎可以同时解释两个键。从研究来看,似乎我需要做单独的轴计算,但我不知道具体如何做,使用我的算法碰撞。如果可能的话,我希望这是程序性的。如果有人能修改我的代码,用一个有效的程序解决方案,我将不胜感激。谢谢。你知道吗
import pygame as pg
import sys
from math import fabs
pg.init()
width = 600
height = 600
gameDisplay = pg.display.set_mode((width, height))
pg.display.set_caption('Block')
white = (255, 255, 255)
red = (255, 0, 0)
clock = pg.time.Clock()
closed = False
FPS = 60
Player_Speed = 200
x, y = 270, 0
vx = 0
vy = 0
collision = False
def Collision(hero, enemy):
global vx, vy, x, y, collision
deltay = fabs(block.centery - ENEMY.centery)
deltax = fabs(block.centerx - ENEMY.centerx)
if deltay < ENEMY.height and deltax < ENEMY.width:
collision = True
if vx > 0:
vx = 0
x = ENEMY[0] - block[2]
if vx < 0:
vx = 0
x = ENEMY[0] + 30
if vy > 0:
vy = 0
y = ENEMY[1] - block[3]
if vy < 0:
vy = 0
y = ENEMY[1] + 30
else:
collision = False
def xy_Text(x, y):
font = pg.font.SysFont("Courier", 16, True)
text = font.render("X: " + str(round(x)), True, (0,150,0))
text1 = font.render("Y: " + str(round(y)), True, (0,150,0))
gameDisplay.blit(text, (0,0))
gameDisplay.blit(text1, (0,14))
while not closed:
for event in pg.event.get():
if event.type == pg.QUIT:
closed = True
dt = clock.tick(FPS)/1000
vx, vy = 0, 0
keys = pg.key.get_pressed()
if keys[pg.K_ESCAPE]:
closed = True
if keys[pg.K_LEFT] or keys[pg.K_a]:
vx = -Player_Speed
if keys[pg.K_RIGHT] or keys[pg.K_d]:
vx = Player_Speed
if keys[pg.K_UP] or keys[pg.K_w]:
vy = -Player_Speed
if keys[pg.K_DOWN] or keys[pg.K_s]:
vy = Player_Speed
if vx != 0 and vy != 0:
vx *= 0.7071
vy *= 0.7071
gameDisplay.fill(white)
ENEMY = pg.draw.rect(gameDisplay, red, (270, 270, 30, 30))
block = pg.draw.rect(gameDisplay, (0, 150, 0), (x, y, 30, 30))
xy_Text(x, y)
x += vx * dt
y += vy * dt
Collision(block, ENEMY)
pg.display.update()
clock.tick(FPS)
pg.quit()
sys.exit()
如果要处理与墙的碰撞,请先沿x轴或y轴移动,如果发生碰撞,请将播放器放回原处,然后对另一个轴执行相同的操作。如果您使用
pygame.Rect
,您可以使用它们的left
、right
、top
和bottom
属性轻松地将播放器设置回块的相应一侧。你知道吗因此,请检查玩家是否与块发生碰撞,如果他/她向右移动(
vx > 0
),然后将hero.right
设置为block.left
,并对其他方向执行相同的操作。如果玩家rect被更新,你还必须返回新的x和y坐标。你知道吗我建议将块(rects)放入
blocks
列表中,您可以将其传递给wall collision函数,然后只使用for循环。你知道吗经过多次修改后,碰撞工作
我搬家了
发生碰撞。你知道吗
我在代码中改变了组织,我总是使用
Rect()
来保持玩家和敌人的位置和大小我还添加了第二个敌人来测试如何检查与许多元素的碰撞。你知道吗
相关问题 更多 >
编程相关推荐