在 p5.js 中击中另一个圆后给圆随机方向

Give circle random direction after hitting another circle in p5.js

我正在创建一个 COVID-19 模拟器,其中模拟中的每个圆圈都是一个人。当两个人互相攻击时,我希望他们 "bounce" 相互偏离的方向是随机的。目前我只是反映了当前的速度,这意味着人们遵循预先定义的路径,即使在彼此弹跳时也是如此。

这是我的"move"函数

 move() {
        if (this.willMove) {
            this.xPos += this.xSpeed;
            this.yPos += this.ySpeed;
        }
    }

这是我进行碰撞检测的地方

collision(other) {
        let distance = dist(this.xPos, this.yPos, other.xPos, other.yPos);

        if (distance < this.personRadius + other.personRadius) {
            this.changeDirection();
            return true;
        } else {
            return false;
        }
    }

改变方向的事情:

changeDirection() {
        this.mirrorXSpeed();
        this.mirrorYSpeed();
    }

    mirrorXSpeed() {
        this.xSpeed = this.xSpeed * -1;
    }

    mirrorYSpeed() {
        this.ySpeed = this.ySpeed * -1;
    }

我试过将速度乘以-0.95,但这只会降低速度。

完整的项目可以在这里找到:https://github.com/perkynades/Simulation-of-COVID19/tree/part1

这可能会有帮助,它会让所有人在被召唤时随机向一个方向弹跳。

您必须将 this.speed 添加到您的 person 构造函数中,并确保角度模式设置为弧度。

changeDirection() {
        //This next line will change the speed by a random amount, 
        //delete it if you don't like it,  
        //or change the range for a different behavior
        this.speed += random(1,3) * random([-1,1])


        let ang = random(PI * 2)
        this.changeXSpeed(ang);
        this.changeYSpeed(ang);
    }

    changeXSpeed(ang) {
        this.xSpeed = this.speed * cos(ang);
    }

    changeYSpeed(ang) {
        this.ySpeed = this.speed * sin(ang);
    }
}

如果你想要更真实的弹跳,我会在 Collision detection 上查看 Chris 课程视频,它在圆圈碰撞时自然掉落到圆圈,即使它不是全部 P5.js,这对我很有帮助,我希望它对你也有帮助。