我必须使用pygame在2d模式下进行游戏,但我不知道如何检测与图像的碰撞
我已经测试了与矩形的碰撞,并且可以正常工作,但是当我尝试将矩形与图像碰撞时,应用程序崩溃了
GPIO_InitStruct.Pin = GPIO_PIN_3;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; // digital Output
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
答案 0 :(得分:3)
PyGame不会碰撞带有矩形的图像,它会碰撞带有矩形的矩形。因此,如果是矩形,则代码需要跟踪图像的位置。
这很容易。最初使用.get_rect()
获得图像的矩形,这为代码提供了一个PyGame rect
对象。然后,代码只需要移动和碰撞矩形,还必须确保始终在矩形的坐标处绘制图像,以使所有内容保持同步。
import pygame,sys
from pygame.locals import *
from random import randint
pygame.init()
ventana=pygame.display.set_mode((1200,600))
pygame.display.set_caption("Jueguiño")
imageVida= pygame.image.load("vida.jpg")
vidaRect = imageVida.get_rect() # <-- Get the Image's Rectangle
posX= randint(0,1200)
posY= randint(0,0)
vidaRect.center = ( posX, posY ) # <-- Position the Rectangle
rectangulo=pygame.Rect(0,0,100,50)
velocidad=0.5
Blanco=(255,255,255)
while True:
ventana.fill(Blanco)
ventana.blit( imageVida, ( vidaRect.x, vidaRect.y ) ) # <-- Draw at the Rectangle
pygame.draw.rect(ventana,(180,70,70),rectangulo)
rectangulo.left,rectangulo.top=pygame.mouse.get_pos()
if rectangulo.colliderect( vidaRect ): # <-- Collide-test the Rectangle
velocidad=0
print("Collision!")
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if posY<1200:
posY+=velocidad
pygame.display.update()
阅读PyGame Sprite Class上的文档可能很有价值。它是用于处理此类工作的完整功能集。起初它有点复杂,但是随后简化了大量后续工作-例如,碰撞的精灵组。 SO上的PyGame答案中有许多使用精灵的例子。
答案 1 :(得分:1)
不要尝试直接与图像碰撞。相反,请使用.get_rect()
函数来获取图像的矩形,以便检查是否有碰撞。