在p5.js中碰到另一个圆后给出圆的随机方向

问题描述 投票:0回答:1

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

这是我的“移动”功能

 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

javascript random corona p5.js direction
1个回答
0
投票

这可能会有所帮助,这将使所有人在被召唤时都朝随机的方向反弹。

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

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,它对我也非常有帮助我希望这也适合您。

© www.soinside.com 2019 - 2024. All rights reserved.