另一个pygame问题。我试图在屏幕上形成一个正方形的方形移动。它工作正常:首先它下降,然后它向右转,然后它开始向上,然后向左,但当它到达应该下降的点时,它根本不会,而是继续向前和向外屏幕。以下是我认为的相关部分
import pygame
from pygame.locals import *
from render import *
from player import *
import sys
pygame.init()
class collisions():
square1x = 50
square1y = 60
direction1 = "down"
vel1y = 0
vel1x = 0
square2x = 0
square2y = 0
direction2 = -1
square3x = 0
square3y = 0
direction3 = -1
square4x = 0
square4y = 0
direction4 = -1
square5x = 0
square5y = 0
direction5 = -1
green = pygame.Color(0,255,0)
def hitbox():
red = pygame.Color(255,0,0)
time = 1000/50
playerhb = pygame.rect.Rect(playerObj.x, playerObj.y,20,20)
if collisions.square1x < 40:
collisions.direction1 = "down"
if collisions.square1y > 200:
collisions.direction1 = "right"
if collisions.square1x > 600:
collisions.direction1 = "up"
if collisions.square1y < 50:
collisions.direction1 = "left"
if collisions.direction1 == "down":
collisions.vel1y = 0.02*time
collisions.vel1x = 0
if collisions.direction1 == "right":
collisions.vel1x = 0.02*time
collisions.vel1y = 0
if collisions.direction1 == "up":
collisions.vel1y = -0.02*time
collisions.vel1x = 0
if collisions.direction1 == "left":
collisions.vel1x = -0.02*time
collisions.vel1y = 0
collisions.square1x = collisions.square1x+collisions.vel1x
collisions.square1y = collisions.square1y+collisions.vel1y
enemy = pygame.rect.Rect(collisions.square1x,collisions.square1y,20,20)
draw(enemy,playerhb)
if enemy.colliderect(playerhb):
pygame.quit()
sys.exit()
pygame.display.flip()
忽略所有其他方形坐标和方向,我打算让更多的方块在屏幕上移动。
答案 0 :(得分:0)
您的“if”序列存在一些问题。您无法仅检查x轴或y轴以决定是否更改方向。您需要检查两个轴(或确保在达到目标时方块返回1个像素。)
我相信下面的代码将解决更改collisions.direction1的问题。
if collisions.square1x < 40 and collisions.square1y < 50:
collisions.direction1 = "down"
if collisions.square1y > 200 and collisions.square1x < 40:
collisions.direction1 = "right"
if collisions.square1x > 600 and collision.square1y > 200:
collisions.direction1 = "up"
if collisions.square1y < 50 and collisions.square1x > 600:
collisions.direction1 = "left"