pygame之rect对象

本文详细介绍了pygame中的Rect对象,包括其主动创建方式、从displaysurface获取、关键属性(如位置、大小和边界)以及常用的方法(如移动、膨胀和碰撞检测)。通过实例演示了如何使用Rect对象进行游戏元素的定位与碰撞处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Rect对象

从本质来看rect对象是一个看不见的矩形区域

Rect对象的创建

  1. 主动创建
pygame.Rect(left,top,width,height)

注:left和top共同组成矩形的左上角坐标,width为矩形的宽,height为矩形的高。

  1. 获取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))
# 创建一个Rect对象
c=screen.get_rect()
# 输出rect对象的尺寸
print(c.size)
# 输出rect对象的中心点坐标
print(c.center)
# 输出rect对象的左上角坐标
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()——按照指定偏移量缩放矩形

#x为正宽度增加,y为正宽度增加
inflate(x,y)

4.inflate_ip()——inflate的原地操作版本

inflate_ip(x,y)

5.contains()——检测两个rect是否完全包含

#检测rect1是否完全包含rect2,若完全包含,返回true,否则返回false
rect1.contains(rect2)

6.collidepoint()——检测坐标是否包含在rect对象中

#rect中是否包含坐标为(x,y)的点,是则true否则false
rect.collidepoint(x,y)

7.colliderect()——检测两个rect是否重叠

#rect1与rect2是否重叠,重叠返回true,否则返回false
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))
#图片转换为surface对象
cat=pygame.image.load("cat.png").convert()
# 创建一个rect
b=cat.get_rect()
# 赋值b对象中心点
b.center=200,260
# 创建一个Rect对象
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()

运行结果如下:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值