Rect对象
从本质来看rect对象是一个看不见的矩形区域
Rect对象的创建
- 主动创建
pygame.Rect(left,top,width,height)
注:left和top共同组成矩形的左上角坐标,width为矩形的宽,height为矩形的高。
- 获取display surface创建Rect对象
display surface.get_rect()
注:该方法创建的rect对象继承了display surface对象的宽、高、尺寸等信息
Rect对象的属性
- X/top——左上角的x坐标
- y/left——左上角的y坐标
- w/width——宽度
- h/height——高度
- size——矩形尺寸,为一个(width,height)的二元组
- bottom——右下角y坐标
- right——右下角x坐标
- centerx——中心点x坐标
- centery——中心点y坐标
- center——中心点坐标,形式为(centerx,centery)
- topleft——左上角坐标
- bottomleft——左下角坐标
- topright——右上角坐标
- bottomright——右下角坐标
- midtop——上边缘中心点坐标
- midleft——左边缘中心点坐标
- midbottom——下边缘中心点坐标
- midright——右边缘中心点坐标
简单示例如下:
import pygame,sys
from pygame.locals import *
pygame.init()
white=(255,255,255)
screen=pygame.display.set_mode(size=(400,300))
c=screen.get_rect()
print(c.size)
print(c.center)
print(c.topleft)
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
输出结果如下图所示:
rect对象的常用方法
1.move()——按照指定的偏移量移动矩形
move(x,y)
注:x为x轴上偏移量正右负左,y为y轴偏移量正下负上。单位均为像素且必须为整数。
2.move_ip()——move()的原地操作版本
move_ip(x,y)
3.inflate()——按照指定偏移量缩放矩形
inflate(x,y)
4.inflate_ip()——inflate的原地操作版本
inflate_ip(x,y)
5.contains()——检测两个rect是否完全包含
rect1.contains(rect2)
6.collidepoint()——检测坐标是否包含在rect对象中
rect.collidepoint(x,y)
7.colliderect()——检测两个rect是否重叠
rect1.collidepoint(rect2)
8.collidelist()——检测多个rect对象与调用该方法的rect是否重叠,返回的是第一个发生重叠的rect对象
collidelist(p_list)
9.collidelistall()——检测多个rect对象与调用该方法的rect是否重叠,返回的是所有发生重叠的rect对象组成的列表
collidelistall(p_list)
综合实例
import pygame,sys
from pygame.locals import *
pygame.init()
white=(255,255,255)
screen=pygame.display.set_mode(size=(400,300))
cat=pygame.image.load("cat.png").convert()
b=cat.get_rect()
b.center=200,260
c=screen.get_rect()
speed=1
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
screen.fill(white)
b.move_ip(speed,0)
if not c.contains(b):
speed=-speed
screen.blit(cat,b)
pygame.display.update()
运行结果如下:
Original: https://blog.csdn.net/weixin_51371629/article/details/125370123
Author: 赟文武
Title: pygame之rect对象
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/782268/
转载文章受原作者版权保护。转载请注明原作者出处!