gpt4 book ai didi

python - pygame,如何获取图形的坐标?

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:49 24 4
gpt4 key购买 nike

我正在尝试让我的绿色方 block 检测与蓝色的碰撞square,但是,我不知道如何构造 if 语句,使其在接触时立即发生碰撞。

如果我使 rect1 的位置 >= 200,100如果越过蓝色方 block 它也会检测到碰撞
g

这是我的代码:

import pygame, sys
import time
import random

pygame.init()

screen = pygame.display.set_mode((640,480)) #Display

running = True
randomList = ("Hello", "Hi", "Why", "Die", "Billy Nye")
#Colors
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
blue = (0,0,255)
green = (0,255,0)

#Time variables
time = pygame.time.Clock()
FPS = 60

#Movement Variables
lead_x = 300
lead_y = 200
lead_x1 = 200
lead_y1 = 100
x_change = 0
y_change = 0
position = (200,100)

#Running MAIN Loop
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

screen.fill(white)
rect2 = pygame.draw.rect(screen, green, [lead_x,lead_y, 50, 50])
rect1 = pygame.draw.rect(screen, blue, [lead_x1,lead_y1, 50 ,50])
pygame.display.update()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -10
if event.key == pygame.K_RIGHT:
x_change = 10
if event.key == pygame.K_UP:
y_change = -10
if event.key == pygame.K_DOWN:
y_change = 10

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
if event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP:
y_change = 0
if event.key == pygame.K_DOWN:
y_change = 0

if lead_x == lead_x1 and lead_y == lead_y1:
print (random.choice(randomList))


lead_x += x_change
lead_y += y_change
time.tick(FPS)


pygame.quit()
quit()

最佳答案

您可以使用collision response

    rect2 = pygame.draw.rect(screen, green, [lead_x,lead_y, 50, 50])
rect1 = pygame.draw.rect(screen, blue, [lead_x1,lead_y1, 50 ,50])
if rect2.colliderect(rect1):
print("BOOM!")

如果你想要坐标:

print(rect2.left,rect2.right,rect2.top,rect2.bottom)

这些是您可以使用的属性,取自 here :

x,y top, left, bottom, right topleft, bottomleft, topright, bottomright midtop, midleft, midbottom, midright center, centerx, centery size, width, height w,h

关于python - pygame,如何获取图形的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31211582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com