Pygame基础8-碰撞

简介: Pygame基础8-碰撞

Collisions

在Pygame中,我们使用矩形来移动物体,并且用矩形检测碰撞。

colliderect检测两个矩形是否碰撞,但是没法确定碰撞的方向。

Rect1.colliderect(Rect2)
# collision -> return Ture 
# else -> return False

collidepoint可以确定一个矩形是否和另一个矩形的某个点碰撞(并确定碰撞方向),但是会很麻烦,并且很容易遗漏某些碰撞。

Rect1.collidepoint(x, y)
# x,y is the point on a Rect

综合考虑之后,

我们通常使用colliderect来检测碰撞,然后根据两个矩形的相对位置确定碰撞方向。

案例

一个矩形(和边框的碰撞)

# rect1
rect1 = pygame.Rect(100, 100, 50, 50)
color1 = (255, 255, 255)
speed_1_x = 5
speed_1_y = 5

def update_rect():
    global speed_1_x, speed_1_y
    rect1.x += speed_1_x
    rect1.y += speed_1_y

    # rect 和边界的碰撞:
    if rect1.left <= 0 and speed_1_x <0:
        speed_1_x *= -1
    elif rect1.right >= witdth and speed_1_x > 0:
        speed_1_x *= -1

    if rect1.top <= 0 and speed_1_y < 0 :
        speed_1_y *= -1
    elif rect1.bottom >= height and speed_1_y > 0:
        speed_1_y *= -1

    pygame.draw.rect(screen, color1, rect1)

# 在主循环中调用 update_rect()
while True:
    ...
    screen.fill((30, 30, 30))
    update_rect()
    ...

添加第二个矩形

注意:除了判断碰撞方向之外,还要判断矩形的速度方向,以防止矩形在碰撞后反复移动。

# rect2
rect2 = pygame.Rect(200, 200, 200, 50)
color2 = (0, 255, 0)
speed_2_x = 0
speed_2_y = 4 # 为了简化,rect2只在竖直方向上移动


def update_rect():
    global speed_1_x, speed_1_y,  speed_2_y
    ...

    rect2.y += speed_2_y
    # rect 和边界的碰撞:
    ...
    if rect2.top <= 0 and speed_2_y < 0 :
        speed_2_y *= -1
    elif rect2.bottom >= height and speed_2_y > 0:
        speed_2_y *= -1

    # rect1 和 rect2的碰撞
    collide_threshold = 20
    if rect1.colliderect(rect2): 
        if abs(rect1.top - rect2.bottom) < collide_threshold and speed_1_y < 0:
            speed_1_y *= -1
        elif abs(rect1.bottom - rect2.top) < collide_threshold and speed_1_y > 0:
            speed_1_y *= -1
        elif abs(rect1.left - rect2.right) < collide_threshold and speed_1_x < 0:
            speed_1_x *= -1
        elif abs(rect1.right - rect2.left) < collide_threshold and speed_1_x > 0:
            speed_1_x *= -1

    

    pygame.draw.rect(screen, color1, rect1)
    pygame.draw.rect(screen, color2, rect2)

完整案例

两个方块的碰撞。为了简化,rect2只在竖直方向上移动。

import sys
import time
import pygame


# Initialize Pygame
pygame.init()

# Set up the display
witdth = 800
height = 600
screen = pygame.display.set_mode((witdth, height))

# Set up the clock
clock = pygame.time.Clock()


# rect1
rect1 = pygame.Rect(100, 100, 50, 50)
color1 = (255, 255, 255)
speed_1_x = 5
speed_1_y = 5

# rect2
rect2 = pygame.Rect(200, 200, 300, 50)
color2 = (0, 255, 0)
speed_2_x = 0 
speed_2_y = 4 # 为了简化,rect2只在竖直方向上移动

def update_rect():
    global speed_1_x, speed_1_y, speed_2_x, speed_2_y
    rect1.x += speed_1_x
    rect1.y += speed_1_y

    #rect2.x += speed_2_x
    rect2.y += speed_2_y

    # rect 和边界的碰撞:
    if rect1.left <= 0 and speed_1_x <0:
        speed_1_x *= -1
    elif rect1.right >= witdth and speed_1_x > 0:
        speed_1_x *= -1

    if rect1.top <= 0 and speed_1_y < 0 :
        speed_1_y *= -1
    elif rect1.bottom >= height and speed_1_y > 0:
        speed_1_y *= -1
    
    
    if rect2.top <= 0 and speed_2_y < 0 :
        speed_2_y *= -1
    elif rect2.bottom >= height and speed_2_y > 0:
        speed_2_y *= -1
        #以 HH:MM:SS 的格式 输出当前时间 
        form_time1 = time.strftime("%H:%M:%S", time.localtime())
        print('rect2 to bottom', 'time= ', form_time1)

    # rect1 和 rect 2的碰撞
    collide_threshold = 20
    if rect1.colliderect(rect2): 
        if abs(rect1.top - rect2.bottom) < collide_threshold and speed_1_y < 0:
            speed_1_y *= -1
            
        if abs(rect1.bottom - rect2.top) < collide_threshold and speed_1_y > 0:
            speed_1_y *= -1
        
        if abs(rect1.left - rect2.right) < collide_threshold and speed_1_x < 0:
            speed_1_x *= -1
         
        if abs(rect1.right - rect2.left) < collide_threshold and speed_1_x > 0:
            speed_1_x *= -1
         

    # Draw the rect
    pygame.draw.rect(screen, color1, rect1)
    pygame.draw.rect(screen, color2, rect2)

while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    screen.fill((30, 30, 30))
    update_rect()
    # Update the display
    pygame.display.flip()

    # Cap the frame rate
    clock.tick(60)
相关文章
|
9月前
|
人工智能 弹性计算 安全
OpenClaw有什么用?本地/阿里云部署+百炼集成+个股分析实战盈利及避坑指南
你是否早已厌倦AI仅能“纸上谈兵”——写方案、改文字却无法落地执行?真正的AI生产力,应该是你设定目标,它全程闭环完成。OpenClaw(Clawdbot)作为首个开源本地部署的AI Agent平台,彻底打破了这一局限:它不是聊天机器人,而是能自动抓取新闻、分拣邮件、监控代码、甚至搭建个股分析模型的“数字员工”,连接飞书、微信等20+平台,数据全程本地化,完全开源可定制。
1318 160
|
6月前
|
人工智能 安全 前端开发
10|Agent Harness 的未来:从代码助手到工程协作系统
AI编程正迈入第三阶段——Agent Harness:AI不再仅补全代码或回答问题,而是深度融入研发全流程——读仓库、改文件、跑测试、连工具、协作者。未来核心在于“可治理的工程协作”,而非单纯自动化。(239字)
357 8
|
6月前
|
弹性计算 网络安全
阿里云服务器ECS实例无法远程连接?连接失败原因解析
阿里云ECS远程连接失败常见原因包括:安全组未放行端口、实例未运行、缺少公网IP/EIP、系统防火墙或SSH服务异常、VPC网络配置错误等。建议按状态→安全组→网络→系统服务顺序逐步排查。详细参考云服务器ECS官方链接:https://t.aliyun.com/U/AZBUsA
743 1
|
7月前
|
存储 NoSQL 数据库
办公Agent的长期记忆设计:记住员工偏好(通知方式、常用模板)
本文揭秘如何为办公Agent设计靠谱的长期记忆系统:通过三层偏好模型(显式/隐式/场景化)、混合存储方案、智能更新遗忘机制及隐私保护设计,让Agent真正“记住你”——不再重复提问,主动适配习惯。不堆术语,只讲实战经验与避坑指南。(239字)
752 0
|
8月前
|
API
阿里云百炼产品优惠券活动:先用后返,最高200元,一键申请,可用于抵扣百炼全量商品
阿里云推出百炼产品优惠券活动,已实名认证的个人和企业用户均可参与,最高可返200元优惠券,用于抵扣阿里云百炼全量商品。活动报名时间为2026年4月27日至5月31日,仅限后付费形式的按量付费订单参与统计。新客5月累计实付金额达门槛即可获券,老客则需5月实付金额比4月有增长。优惠券包括20元、100元、200元三档,6月20日前发放,有效期30天,每用户限领一次,不可叠加使用。
|
9月前
|
Web App开发 人工智能
火语言 RPA:模拟真人操作 —— 微博超话签到、发布互动贴与浏览全流程案例
本案例基于火语言RPA,自动化完成微博超话签到、发帖互动及10次滚动浏览,精准模拟真人行为。支持指定Chrome路径与用户配置,智能判断签到弹窗、条件执行操作,并自动关闭浏览器释放资源,有效提升账号活跃度。
666 2
|
机器学习/深度学习 存储 算法
【LeetCode 热题100】347:前 K 个高频元素(详细解析)(Go语言版)
这篇文章详细解析了力扣热题 347——前 K 个高频元素的三种解法:哈希表+小顶堆、哈希表+快速排序和哈希表+桶排序。每种方法都附有清晰的思路讲解和 Go 语言代码实现。小顶堆方法时间复杂度为 O(n log k),适合处理大规模数据;快速排序方法时间复杂度为 O(n log n),适用于数据量较小的场景;桶排序方法在特定条件下能达到线性时间复杂度 O(n)。文章通过对比分析,帮助读者根据实际需求选择最优解法,并提供了完整的代码示例,是一篇非常实用的算法学习资料。
1082 90
|
SQL 存储 运维
数据库生态工具&架构方案| 学习笔记(一)
快速学习数据库生态工具&架构方案
1427 0
数据库生态工具&架构方案| 学习笔记(一)
|
Shell Linux
shell sleep 睡眠命令
shell sleep 睡眠命令