不同大小圆形的碰撞
创始人
2025-01-08 11:30:20
0

使用p5.js库中的createVector()、dist()、mag()和normalize()函数计算碰撞后的速度方向和大小。

示例代码如下:

let circle1, circle2;

function setup() {
  createCanvas(400, 400);
  circle1 = new Circle(100, 100, 30);
  circle2 = new Circle(200, 200, 50);
}

function draw() {
  background(220);
  
  circle1.update();
  circle2.update();
  if (circle1.collide(circle2)) {
    circle1.handleCollision(circle2);
  }
  
  circle1.display();
  circle2.display();
}

class Circle {
  constructor(x, y, r) {
    this.pos = createVector(x, y);
    this.vel = createVector(3, 1);
    this.r = r;
    this.color = color(random(255), random(255), random(255));
  }
  
  update() {
    this.pos.add(this.vel);
    if (this.pos.x <= this.r || this.pos.x >= width - this.r) {
      this.vel.x *= -1;
    }
    if (this.pos.y <= this.r || this.pos.y >= height - this.r) {
      this.vel.y *= -1;
    }
  }
  
  display() {
    noStroke();
    fill(this.color);
    ellipse(this.pos.x, this.pos.y, this.r * 2);
  }
  
  collide(other) {
    let distance = dist(this.pos.x, this.pos.y, other.pos.x, other.pos.y);
    return distance <= this.r + other.r;
  }
  
  handleCollision(other) {
    let direction = createVector(other.pos.x - this.pos.x, other.pos.y - this.pos.y);
    let magnitude = direction.mag();
    direction.normalize();
    let speed = (this.vel.mag() + other.vel.mag()) / 2;
    this.vel = direction.copy().mult(speed);
    other.vel = direction.copy().mult(-speed);
  }
}

在这个示例中,我们定义了Circle类,该类具有update()、display()、collide()和handleCollision()等方法。我们在setup()函数中创建了两个Circle对象,并在draw()函数中更新和显示它们。当两个圆形发生碰撞时,我们使用handleCollision()方法计算它们碰撞后的速度方向和大小,然后分别将新的速度分配给两个圆形的vel属性。

使用p5.js库中的函数,我们可以轻松地解决不同大小圆形的

相关内容

热门资讯

透视了解(WepoKe)透视辅... 1、透视了解(WepoKe)透视辅助技巧(WePoKe透明挂)都是是有挂(详细透视黑科技教程)。2、...
透视有挂(德扑之星有猫腻)wp... 透视有挂(德扑之星有猫腻)wpk数据透视(详细辅助AI教程)原先是有挂1、许多玩家不知道德扑之星有猫...
透视玄学(WePoke)透明挂... 透视玄学(WePoke)透明挂辅助安装(wepoke有挂)确实存在有挂(详细透视AA德州教程);1分...
透视挂透视(微扑克ai辅助工具... 透视挂透视(微扑克ai辅助工具)fishpoker软件辅助(详细辅助教你攻略)总是有挂1、很好的工具...
透视辅助(wEpOke)外挂透... 透视辅助(wEpOke)外挂透明挂辅助工具(wepoke模拟器)本来有挂(详细透视可靠教程)是一款可...
透视能赢(wepoke真的有挂... 透视能赢(wepoke真的有挂)wepoke软件(详细辅助曝光教程)本来真的是有挂1、在wepoke...
透视免费(微扑克辅助软件)扑克... 透视免费(微扑克辅助软件)扑克时间后台数据被攻破(详细辅助扑克教程)确实有挂;是一款可以让一直输的玩...
透视新版(wEpoKe)透明挂... 透视新版(wEpoKe)透明挂辅助插件(wepoke模拟器)原先是真的有挂(详细透视黑科技教程);原...
透视代打(WePoke)外挂透... 透视代打(WePoke)外挂透明挂辅助挂(wepoke的确有挂)原本是有挂(详细透视德州论坛)是一款...
透视免费(德扑数据软件)We辅... 透视免费(德扑数据软件)We辅poker助(详细辅助必胜教程)本来存在有挂是一款可以让一直输的玩家,...