繁体   English   中英

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

[英]pygame, how do you get coordinates of a graphic?

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

如果我这样做,以使rect1的位置> = 200,100,如果也越过蓝色方块,它将检测到碰撞
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()

您可以使用碰撞响应

    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)

这些是您可以使用的属性,可从此处获取

x,y上,左,下,右上左,下左,上右,右下中上,左上,中下,右中中心,centerx,居中大小,宽度,高度w,h

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM