当前位置:网站首页>【Pygame 学习笔记】5.rect对象的碰撞检测
【Pygame 学习笔记】5.rect对象的碰撞检测
2022-07-17 17:13:00 【Leleprogrammer】
这一次,我们来学习rect对象的碰撞检测
首先,给出框架代码:
import pygame
from pygame.locals import *
import sys
class Game:
def __init__(self):
pygame.init()
self.W,self.H=800,800
self.screen=pygame.display.set_mode((self.W,self.H))
pygame.display.set_caption("【Pygame 学习笔记】")
def listen(self):
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()
def draw(self):
self.screen.fill((255,255,255))
def run(self):
while True:
self.listen()
self.draw()
pygame.display.update()
if __name__ == '__main__':
game=Game()
game.run()
首先,是rect与点的碰撞,用rect自带的colliderect函数,返回值为bool
collidepoint(x,y)
collidepoint([x,y])
这是两种写法,比如,我们先画一个正方形,在draw中添加:
rect=pygame.draw.rect(self.screen,(255,0,0),(10,10,100,100))
然后进行碰撞检测:
if rect.collidepoint(pygame.mouse.get_pos()):
print(True)
这样,只要碰到鼠标就会输出True
接下来,我们来学习两个rect的碰撞,在制作很多游戏时都需要用到,我们去除上方检测碰撞的代码,保留绘制rect的代码,然后绘制第二个图形:
rect2=pygame.draw.rect(self.screen,(0,0,255),(self.x,10,40,40))
这里我们第二个图形需要在窗口中不断移动,碰到边缘就反弹,当碰到第一个图形的时候就输出True,这里就需要用到了colliderect函数,先定义两个变量在初始化中
self.x=90
self.speed=0.2
在绘制rect2的时候,先更新位置
self.x+=self.speed
然后进行碰撞操作和检测碰撞边缘的操作,检测碰撞边缘很简单,使用rect自带的一些参数与窗口的一些长宽进行比较即可,然后将速度设置为它的相反数
if rect.colliderect(rect2):
print(True)
if rect2.right>=self.W or rect2.left<0:
self.speed=-self.speed
这样就可以啦,当连哥哥图形碰撞时,程序会一直输出True
参考代码如下:
import pygame
from pygame.locals import *
import sys
class Game:
def __init__(self):
pygame.init()
self.W,self.H=800,800
self.screen=pygame.display.set_mode((self.W,self.H))
pygame.display.set_caption("【Pygame 学习笔记】")
self.x=90
self.speed=0.2
def listen(self):
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()
def draw(self):
self.screen.fill((255,255,255))
rect=pygame.draw.rect(self.screen,(255,0,0),(10,10,100,100))
# if rect.collidepoint(pygame.mouse.get_pos()):
# print(True)
self.x+=self.speed
rect2=pygame.draw.rect(self.screen,(0,0,255),(self.x,10,40,40))
if rect.colliderect(rect2):
print(True)
if rect2.right>=self.W or rect2.left<0:
self.speed=-self.speed
def run(self):
while True:
self.listen()
self.draw()
pygame.display.update()
if __name__ == '__main__':
game=Game()
game.run()
rect还有一些检测碰撞的方法:collidelist,collidedict等等,collidelist传入一个列表,列表中是多个rect,collidedict传入rect的字典,也差不多,但是不会特别常用,这里就不讲解啦~
喜欢我的文章的话别忘了点赞收藏+关注哦~
谢谢支持~
边栏推荐
- PostgreSQL function usage record
- 最小交換次數
- Yunxi focuses on store broadcast solutions to accelerate global layout
- 稳超胜算,历9弥新 | 2022金仓创新产品发布会顺利召开
- 2022全球开发者薪资曝光:中国排第19名,平均年薪23,790美元
- 整理了一份通用的内存管理驱动代码
- If you merge cells by Excel, export excelutils
- Differences between get requests and post requests and usage examples
- Harmonyos quick start: Hello World
- Nombre minimal d'échanges
猜你喜欢
AI is the designer who knows you best? Let users generate digital clothing "by heart" Adidas ozworld
Metal organic framework / nitrogen carbide nano sheet (uio-66/hocn) composite | mil-101 loaded Au Pd alloy nanoparticles | chemical reagent MOF customization
AE how to make Nebula particle special effects
基于STM32设计的云端健康管理系统(采用阿里云物联网平台)
Ultrasonic sensor (chx01) learning notes Ⅲ - I2C reading and writing operation
ATT&CK实战系列——红队实战(—)
[email protected] Support) | uio-66/coso composite | zif-67 nanocrystalline sur"/>
Copper sulfide nanoparticles /zif-8 Composites( [email protected] Support) | uio-66/coso composite | zif-67 nanocrystalline sur
OpenCV:06形态学
Interview difficulties: difficulties in implementing distributed session, this is enough!
Investment logic in market "uncertainty" 2020-03-18
随机推荐
[C language programming 7] BTB model
Uio-66 - (COOH) 2 modified polyamide nanofiltration membrane | zif-8/pvp composite nanofiber membrane | uio-66-nh2 modified polyamide nanofiltration membrane
Committer identity unknown *** Please tell me who you are...
FFmpeg转换视频格式与导出GIF动态图的方法
虞美人·寄公度
Acwing786. The kth number
PostgreSQL 函数使用记录
R语言--Cox模型校准曲线原理(一)数据来源
AI is the designer who knows you best? Let users generate digital clothing "by heart" Adidas ozworld
运维小白成长记—架构第6周
Can you view MySQL data table structure in two ways?
Acwing4405. Statistical submatrix
图执行引擎那些事(二)
Ultrasonic sensor (ch101 & ch201) - I
Label ball problem
Acwing4405. 统计子矩阵
How to invest scientifically and rationally when the global financial crisis strikes? 2020-03-17
Enrollment publicity - Jiangnan University
逻辑运算符1(阁瑞钛伦特软件-九耶实训)
Yunxi and Tencent cloud have reached a strategic cooperation to accelerate the expansion of the global live broadcast market