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

标签 python graph pygame coordinates python-3.3

我正在尝试让我的绿色方 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/

相关文章:

python - 家庭作业 - 在两个行号之间打印文件行

Python pygame - 带有 float 的平滑移动

visual-studio-code - 如何让某些 pygame 模块在 VSC 中工作?其他修复不起作用

python - 对 Pandas DataFrame 中存在非数字值的所有列求和

python - Keras 中 GAN 损失的指标名称

python - 从 PyPI : root files not installed 安装包时出现问题

jquery - 创建 jquery/html5 Canvas 图

javascript - 如何在 cytoscape.js 中绘制短边

algorithm - 最大二分图 (1,n) "matching"

python - 如何使用 pygame.mixer 重复播放音乐?