Моя функция столкновения не работает в PygamePython

Программы на Python
Ответить
Anonymous
 Моя функция столкновения не работает в Pygame

Сообщение Anonymous »

Проблема в том, как работает столкновение: код работает для столкновения, которое происходит сбоку, но по какой-то причине при движении сверху или снизу ввод со стороны приводит к «перепрыгиванию» на противоположную сторону. блокирует место, куда игрок пытается двигаться, а не обычное плавное движение.
Соответствующий код:
import pygame

import sys

# Initializing Pygame
pygame.init()

# Defining the dimentions for our sacreen
WINDOW_WIDTH = 1220
WINDOW_HEIGHT = 720

# Defining the color to print in the screen
BG_COLOR = (255,255,255)

#Constants
SPEED = 500
MOUSEBASEDMOVEMENT = False

# The screen is almost ready, this is just the definition
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# Adding our awesone caption to show in the top of our fresh screen
pygame.display.set_caption("Maze Racer")

# clock
clock = pygame.time.Clock()

#Colour Themes
SelectedMaze = 1
if SelectedMaze == 0:
#Blue
BlockColour = (21,96,130)
BackgroundColour = (255,255,255)
screen.fill(BackgroundColour)
elif SelectedMaze == 1:
#Grey
BlockColour = (116,116,116)
BackgroundColour = (255,255,255)
screen.fill(BackgroundColour)
elif SelectedMaze == 2:
#Red
BlockColour = (128,53,14)
BackgroundColour = (255,255,255)
screen.fill(BackgroundColour)
elif SelectedMaze == 3:
#Yellow
BlockColour = (255,255,0)
BackgroundColour = (58,58,58)
screen.fill(BackgroundColour)

# setup dude
dude = pygame.image.load('/Users/tom/Coursework-Project/Player Sprite - Coursework.png').convert_alpha()
dude = pygame.transform.smoothscale_by(dude, 0.04)
dude_x = 100
dude_y = 100
dude_vel_x = 0
dude_vel_y = 0

# adding the defs to check if the input is to the left/right
def is_button_down(event):
return event.type == pygame.MOUSEBUTTONDOWN

def is_button_up(event):
return event.type == pygame.MOUSEBUTTONUP

def is_input_left_active(event):
return event.type == pygame.KEYDOWN and (event.key == pygame.K_a or event.key == pygame.K_LEFT)

def is_input_down_active(event):
return event.type == pygame.KEYDOWN and (event.key == pygame.K_s or event.key == pygame.K_DOWN)

def is_input_up_active(event):
return event.type == pygame.KEYDOWN and (event.key == pygame.K_w or event.key == pygame.K_UP)

def is_input_right_active(event):
return event.type == pygame.KEYDOWN and (event.key == pygame.K_d or event.key == pygame.K_RIGHT)

#Draw a rectangle - diagonal collision on top not working
def drawrectangle(x,y,colour,xscale,yscale):
global screen,dude_x,dude_y,dude_vel_x,dude_vel_y
pygame.draw.rect(screen,(colour), (x,y,100*xscale,100*yscale))
#Check if y is correct before limiting x axis movement
if dude_y + dude.get_rect().height > y and dude_y < y + 100*yscale:
if(dude_x + dude.get_rect().width > x) and (dude_x < x + 100*xscale) :
if dude_vel_x > 0:
dude_x = x - dude.get_rect().width
elif dude_vel_x < 0:
dude_x = x + 100*xscale
#Check if x is correct before limiting y axis movement
if dude_x + dude.get_rect().width > x and dude_x < x + 100*xscale:
if(dude_y + dude.get_rect().height > y) and (dude_y < y + 100*yscale):
if dude_vel_y > 0:
dude_y = y - dude.get_rect().height
elif dude_vel_y < 0:
dude_y = y + 100*yscale

# Flag to run our loop, it's optional in this example but useful to get used too
while True:
dt = clock.tick(60) / 1000
#This for loop always looks at user input and responds accordingly
for event in pygame.event.get():
# And once is equal when a user closes the window
# it will close the current window in execution
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

if MOUSEBASEDMOVEMENT:
MousePos = pygame.mouse.get_pos()
if MousePos[1] > dude_y:
dude_vel_y += SPEED/10 * dt
if dude_vel_y < 0.5:
dude_vel_y = 0

if MousePos[1] < dude_y:
dude_vel_y -= SPEED/10 * dt
if dude_vel_y > 0.5:
dude_vel_y = 0

if MousePos[0] > dude_x:
dude_vel_x += SPEED/10 * dt
if dude_vel_x < 0.5:
dude_vel_x = 0

if MousePos[0] < dude_x:
dude_vel_x -= SPEED/10 * dt
if dude_vel_x > 0.5:
dude_vel_x = 0

if is_input_left_active(event):
dude_vel_x -= SPEED * dt

if is_input_right_active(event):
dude_vel_x += SPEED * dt

if is_input_down_active(event):
dude_vel_y += SPEED * dt

if is_input_up_active(event):
dude_vel_y -= SPEED * dt

if not MOUSEBASEDMOVEMENT:
if event.type == pygame.KEYUP or is_button_up(event):
if event.key == pygame.K_s or event.key == pygame.K_w or event.key == pygame.K_DOWN or event.key == pygame.K_UP:
dude_vel_y = 0
if event.key == pygame.K_a or event.key == pygame.K_d or event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dude_vel_x = 0

# This is the magic sentence where the screen finally renders BG_COLOR,
screen.fill(BG_COLOR)

# printing the dude image
screen.blit(dude, (dude_x, dude_y))

dude_x += dude_vel_x
dude_y += dude_vel_y

# detect bounds and limiting the dude in the screen
if(dude_x = screen.get_height()):
dude_y = screen.get_height() - dude.get_rect().height

#Call functions to draw the shapes on screen
testcol = (155,155,155)
drawrectangle(560,360,BlockColour, 1,1)
# This method refreshes all the screen, is part of a good practice keep it here
pygame.display.flip()

#clock
clock.tick(60) # Limit to 60 FPS

Я попробовал поменять порядок операторов if, и в результате поменялась ось, на которой возникла проблема.
Это функция вызывает проблемы:
#Draw a rectangle - diagonal collision on top not working
def drawrectangle(x,y,colour,xscale,yscale):
global screen,dude_x,dude_y,dude_vel_x,dude_vel_y
pygame.draw.rect(screen,(colour), (x,y,100*xscale,100*yscale))
#Check if y is correct before limiting x axis movement
if dude_y + dude.get_rect().height > y and dude_y < y + 100*yscale:
if(dude_x + dude.get_rect().width > x) and (dude_x < x + 100*xscale) :
if dude_vel_x > 0:
dude_x = x - dude.get_rect().width
elif dude_vel_x < 0:
dude_x = x + 100*xscale
#Check if x is correct before limiting y axis movement
if dude_x + dude.get_rect().width > x and dude_x < x + 100*xscale:
if(dude_y + dude.get_rect().height > y) and (dude_y < y + 100*yscale):
if dude_vel_y > 0:
dude_y = y - dude.get_rect().height
elif dude_vel_y < 0:
dude_y = y + 100*yscale


Подробнее здесь: https://stackoverflow.com/questions/793 ... -in-pygame
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»