当前位置:网站首页>[pyGame learning notes] 5 Collision detection of rect objects
[pyGame learning notes] 5 Collision detection of rect objects
2022-07-19 13:04:00 【Leleprogrammer】
This time, , Let's learn rect Collision detection of objects
First , Give the frame code :
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 Learning notes 】")
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()First , yes rect Collision with points , use rect Self contained colliderect function , The return value is bool
collidepoint(x,y)
collidepoint([x,y])
These are two ways of writing , such as , Let's draw a square first , stay draw Add :
rect=pygame.draw.rect(self.screen,(255,0,0),(10,10,100,100))
Then conduct collision detection :
if rect.collidepoint(pygame.mouse.get_pos()):
print(True)such , As long as you touch the mouse, it will output True
Next , Let's learn two rect Collision , It is necessary to make many games , We remove the collision detection code above , Keep drawing rect Code for , Then draw the second figure :
rect2=pygame.draw.rect(self.screen,(0,0,255),(self.x,10,40,40))Here, our second figure needs to move constantly in the window , Rebound on the edge , Output when you encounter the first figure True, You need it here colliderect function , First define two variables in initialization
self.x=90
self.speed=0.2Drawing rect2 When , Update the location first
self.x+=self.speedThen carry out the collision operation and the operation of detecting the collision edge , Detecting collision edges is simple , Use rect Compare some parameters with the length and width of the window , Then set the speed to its opposite number
if rect.colliderect(rect2):
print(True)
if rect2.right>=self.W or rect2.left<0:
self.speed=-self.speedThat's it , When the figures of brother Lian collide , The program will always output True
The reference codes are as follows :
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 Learning notes 】")
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 There are also some ways to detect collisions :collidelist,collidedict wait ,collidelist Pass in a list , There are multiple in the list rect,collidedict Pass in rect Dictionary , Also almost , But not particularly commonly used , I won't explain it here ~
If you like my article, don't forget to like it + Pay attention to ~
Thank you for your support ~
边栏推荐
- 【Try to Hack】arp和arp欺骗
- 虞美人·寄公度
- R语言--Cox模型校准曲线原理(一)数据来源
- If you merge cells by Excel, export excelutils
- AE如何制作星云粒子特效
- Label ball problem
- PostgreSQL function usage record
- About the "bottom reading" mentality, it makes you exhausted 2020-03-15
- Ultrasonic sensor (ch101 & ch201) - Ⅱ
- Metal organic framework / nitrogen carbide nano sheet (uio-66/hocn) composite | mil-101 loaded Au Pd alloy nanoparticles | chemical reagent MOF customization
猜你喜欢

2022 global developer salary exposure: China ranks 19th, with an average annual salary of $23790

稳超胜算,历9弥新 | 2022金仓创新产品发布会顺利召开

VMware导入ova/ovf虚拟机文件

收益风险比:投资机会最重要指标 2020-03-14

Is the career direction of test / development programmers over 35 a turning point in the workplace?

Label ball problem

AI is the designer who knows you best? Let users generate digital clothing "by heart" Adidas ozworld

又错了,字节对齐及#pragma pack的使用

About the "bottom reading" mentality, it makes you exhausted 2020-03-15

Amino metal organic framework material Fe MOF, fe-mil-88nh2 | Zr based metal organic framework catalyst (pt-uio-66) | Qiyue biology
随机推荐
懒到骨子里了,我在CSDN写文章都懒得自己写了,基于selenium模拟写文章
MOF customized product | n-k2ti4o9/g-c3n4/uio-66 ternary composite | paper based au-aginse2-zif-8 Nanocomposite
Cobalt iron bimetallic organic skeleton cox/mil-100 (FE) | [email protected]
Investment logic in market "uncertainty" 2020-03-18
Equivalent domain name
35岁以上的测试/开发程序员职业生涯走向,是职场转折点吗?
最懂你的服装设计师是AI?让用户 “凭心意” 生成数字服装#Adidas OZWORLD
基于STM32设计的云端健康管理系统(采用阿里云物联网平台)
When will the moon appear
Uio-66 | fe3o4/cu3 (BTC) 2 metal organic framework (MOF) nanocomposites supported on silver nanoparticles | nagdf4:yb, er upconversion nanoparticles @zif-8
VMware imports ova/ovf virtual machine files
Gold nanoparticles modified mil-101 framework material (AuNPs / mil-101) / loaded cof-tppa-1 (Au NPs / cof-tppa-1) | Qiyue reagent
About the "bottom reading" mentality, it makes you exhausted 2020-03-15
Redis logical cluster creation
Growth of operation and maintenance Xiaobai - week 6 of Architecture
Nitrogen heterocyclic molecule modified uio-66-nh2 | polyethyleneimine modified uio-66-nh2| [email protected] @Zif67 nanomaterial
FFmpeg转换视频格式与导出GIF动态图的方法
二叉树2—对称性递归问题
Enrollment publicity - Jiangnan University
[C language programming 8] branch predictor