Pygame的问题!碰撞功能无法检测到两个碰撞时的碰撞!虽然没有给出任何错误消息,但是它们之间只是相互影响。为什么这个以及如何解决?连续几天一直在努力解决这个问题!假设问题点标有注释。提前谢谢!
#Start it up
import pygame
pygame.init()
fpsClock = pygame.time.Clock()
#surface = pygame.display.set_mode((640,480),pygame.FULLSCREEN)
surface = pygame.display.set_mode((640,480))
pygame.display.set_caption('Game Skeleton')
#Globals and Misc.
x = 10
y = 350
l = 15
w = 35
moveX=0
moveY=0
characterRect= pygame.Rect(x,y,l,w)
ground = pygame.Rect(0,385,700,385)
ledge1= pygame.Rect(310,330,20,20)
jump=0
white = (255,255,255)
black = (0,0,0)
firebrick = (178,34,34)
blockRects = [ground,ledge1]
contact = False
playOn = True
var=0
#standingLeft = pygame.image.load("images/
#standingRight = pygame.image.load("images/
#walkingRight = pygame.image.load("images/
#walkingLeft = pygame.image.load("images/
#straightJumping = pygame.image.load("images/
#rightJumping = pygame.image.load("images/
#leftJumping = pygame.image.load("images/
#inquire = pygame.image.load("images/
#climbing = pygame.image.load("images/
#Game Loop
while playOn:
#Take user input
for event in pygame.event.get():
if(event.type==pygame.KEYDOWN):
if(event.key==pygame.K_RIGHT):
moveX=1
if(event.key==pygame.K_LEFT):
moveX=-1
if(event.key==pygame.K_UP):
moveY=-1
if(event.key==pygame.K_DOWN):
moveY=1
if(event.key==pygame.K_SPACE):
jump=1
if(event.key==pygame.K_ESCAPE):
playOn = False
if(event.type==pygame.KEYUP):
if(event.key==pygame.K_RIGHT):
moveX=0
if(event.key==pygame.K_LEFT):
moveX=0
if(event.key==pygame.K_UP):
moveY=0
if(event.key==pygame.K_DOWN):
moveY=0
#If user input said to move
x = x + moveX
y = y + moveY
#Jump Code
if(jump>0 and contact==False):
y=y-jump - 1
var=var+1
if(var>45):
jump=0
var=0
if(contact==False):
y=y+1
if(contact!=True):
contact==False
#These two "ifs" don't appear to be working D:
if (ground.colliderect(characterRect)):
y=y-1
contact == True
if(ledge1.colliderect(characterRect)):
y=y-1
contact == True
#Renderings
surface.fill(white)
pygame.draw.rect(surface,black,(x,y,l,w))
pygame.draw.rect(surface,firebrick,(0,385,700,385))
pygame.draw.rect(surface,firebrick,(340,350,100,5))
fpsClock.tick(80)
pygame.display.flip()
pygame.quit()
答案 0 :(得分:2)
您正在初始化:
characterRect= pygame.Rect(x,y,l,w)
然后你独立更新x,y,l,w变量并忘记characterRect
,所以characterRect rect总是在同一个位置。
您可以直接在characterRect
上进行更新,也可以在检查y
之前指定新的colliderect
值。
@Justin Pearce更正也很重要,否则您的代码将无法正常运行。
另请查看PEP 8。对于外观漂亮的python代码,您应该删除if
条件周围的括号。
答案 1 :(得分:1)
你有这个:
if(contact!=True):
contact==False
#These two "ifs" don't appear to be working D:
if (ground.colliderect(characterRect)):
y=y-1
contact == True
if(ledge1.colliderect(characterRect)):
y=y-1
contact == True
不应该吗?:
if(contact!=True):
contact=False
#These two "ifs" don't appear to be working D:
if (ground.colliderect(characterRect)):
y=y-1
contact = True
if(ledge1.colliderect(characterRect)):
y=y-1
contact = True
Double equals是比较运算符,而不是赋值运算符。