Python+OpenCV实现动态碰撞小球动画

本文将利用Python中的CV2库,实现随机生成多个大小、颜色和运动速度各异的小球,并在窗口中模拟它们碰撞边界后的反弹效果。

import cv2
import numpy as np

# 定义画布的宽度和高度
canvas_width = 800
canvas_height = 600

# 定义小球的数量
num_balls = 10

# 小球的半径范围
min_radius = 10
max_radius = 50

# 定义小球的颜色范围(BGR格式)
min_color = (0, 0, 0)
max_color = (255, 255, 255)

# 定义小球的初始位置和速度
balls = []
for _ in range(num_balls):
    radius = np.random.randint(min_radius, max_radius)
    color = (
        np.random.randint(min_color[0], max_color[0]),
        np.random.randint(min_color[1], max_color[1]),
        np.random.randint(min_color[2], max_color[2])
    )
    x = np.random.randint(radius, canvas_width - radius)
    y = np.random.randint(radius, canvas_height - radius)
    dx = np.random.randint(-5, 5)
    dy = np.random.randint(-5, 5)
    balls.append((x, y, dx, dy, radius, color))

# 创建画布
canvas = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

# 运动循环
while True:
    # 清空画布
    canvas.fill(0)
    
    # 更新小球的位置
    for i, (x, y, dx, dy, radius, color) in enumerate(balls):
        x += dx
        y += dy
        
        # 检查小球是否碰到边界,如果是则反弹
        if x - radius < 0 or x + radius > canvas_width:
            dx = -dx
        if y - radius < 0 or y + radius > canvas_height:
            dy = -dy
        
        # 更新小球的信息
        balls[i] = (x, y, dx, dy, radius, color)
        
        # 在画布上绘制小球
        cv2.circle(canvas, (x, y), radius, color, -1)
    
    # 显示画布
    cv2.imshow('Bouncing Balls', canvas)
    
    # 检查是否按下了 ESC 键,如果是则退出循环
    if cv2.waitKey(1) == 27:
        break

# 关闭窗口
cv2.destroyAllWindows()

代码解析:

  1. 导入库: 导入 cv2numpy 库。
  2. 设置参数: 设置画布大小、小球数量、半径范围、颜色范围等参数。
  3. 初始化小球: 使用循环创建多个小球,每个小球具有随机的位置、速度、半径和颜色。
  4. 创建画布: 创建一个黑色画布用于绘制小球。
  5. 运动循环:
    • 清空画布,准备绘制新一帧动画。
    • 遍历每个小球,更新其位置并检查是否碰撞边界。
    • 如果小球碰撞边界,则反转其速度方向以实现反弹效果。
    • 在画布上绘制当前帧的小球。
    • 显示画布,刷新动画。
    • 检测键盘输入,如果按下 'ESC' 键则退出循环。
  6. 关闭窗口: 退出循环后,关闭所有OpenCV窗口。

运行代码:

  1. 确保已安装 cv2numpy 库。
  2. 运行代码,将弹出一个窗口显示动态碰撞的小球动画。

注意:

  • 代码中的速度是基于像素的,可以根据需要调整速度范围以改变小球运动的快慢。
  • 可以修改代码中的参数,例如小球数量、大小、颜色等,以创建不同的动画效果。
  • 此代码模拟的是理想情况下的碰撞,没有考虑能量损失和旋转等因素。

原文地址: https://www.cveoy.top/t/topic/cisx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录