I'm having issues getting this collision to work 100%. If I only press one key at a time, the collision seems to work fine, but if I press a key and continue pressing, while colliding, then press another key, the collision seems to account for both keys at the same time. From researching, it seems like I need to do separate axis calculations, but I'm not sure exactly how to do that, using the algorithm I have for collision. I want this to be procedural style, if possible. If anyone could amend my code, with a working procedural solution, I'd greatly appreciate it. Thanks.
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()