pygame,你如何获得图形的坐标?

时间:2015-07-03 17:09:37

标签: python graph pygame coordinates python-3.3

我正试图让我的绿色方块检测到与蓝色的碰撞 但是,我不知道如何构造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()

1 个答案:

答案 0 :(得分:1)

您可以使用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   顶部,左侧,底部,右侧   topleft,bottomleft,topright,bottomright   midtop,midleft,midbottom,midright   center,centerx,centery   大小,宽度,高度   W,H