首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >p5js移动圆碰撞检测

p5js移动圆碰撞检测
EN

Stack Overflow用户
提问于 2021-05-16 22:47:18
回答 1查看 49关注 0票数 0

我需要一些关于p5js代码的帮助。我已经画了一个简单的草图,其中4个圆圈以给定的速度移动。我想要做的是当任何一个圆接触到另一个圆时,改变填充颜色。我认为问题是我在我的构造函数对象中初始化椭圆的x和y值,我需要随着圆的移动而更新它,但我不确定如何做到这一点。

代码语言:javascript
复制
// Declare objects
let bubble1;
let bubble2;
let bubble3;
let bubble4;
var centDistance;

function setup() {
  createCanvas(windowWidth, windowHeight);
  ellipseMode(CENTER);

  // Create objects
  bubble1 = new Bubble(50, 0, 2);
  bubble2 = new Bubble(50, 2, 0);
  bubble3 = new Bubble(50, -2, 0);
  bubble4 = new Bubble(50, 0, -2);

}

function draw() {
  background(0); 
 
  bubble1.display();
  bubble2.display();
  bubble1.move();
  bubble2.move();
  bubble3.display();
  bubble3.move();
  bubble4.display();
  bubble4.move();

  var d = dist(bubble1.x, bubble1.y, bubble2.x, bubble2.y);
  if (d < bubble1.r+bubble2.r) {
    bubble1.changeCol();
    bubble2.changeCol();
  }

} 

class Bubble {
    constructor(r, xSpeed, ySpeed) {
        this.x = width/2; 
        this.y = height/2;
        this.r = r;
        this.xSpeed = xSpeed;
        this.ySpeed = ySpeed; 
        this.fillColor = color(255);

        this.move = function () {
            if (this.x>width/2+200 || this.x<width/2-200) {
                this.xSpeed = -this.xSpeed;
            }
            if (this.y>height/2+200 || this.y<height/2-200) {
                this.ySpeed = -this.ySpeed;
            }
            this.x += this.xSpeed;
            this.y += this.ySpeed;
        }

        this.display = function() {
            fill(this.fillColor);
            stroke(255);
            ellipse(this.x, this.y, 2*this.r);
        }

        this.changeCol = function () {
            this.fillColor = color(0);
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-05-16 23:51:18

问题是,当动画开始时,两个圆发生碰撞,本例中为bubble1和bubble2。

然后,在changeCol函数中将颜色更改为黑色,这两个颜色都会变成黑色,然后一直保持不变。

你的代码工作正常,问题是this.fillColor不会在每次重新渲染时被重新初始化,因为你已经在setup函数中实例化了你的对象,所以当它们没有接触到其他圆时,你必须重新绘制它们。

代码语言:javascript
复制
  if (d < bubble1.r+bubble2.r) {
    bubble1.changeCol(255);
    bubble2.changeCol(255);
  } else {
    bubble1.changeCol(0);
    bubble2.changeCol(0);
  }

  this.changeCol = function (col) {
      this.fillColor = color(col);
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67558015

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档