p5.js 让球从中间向外移动并向不同的方向分裂

p5.js Getting the ball to move out from the middle and split into different directions

我正在制作一个名为 popThatBall 的简单点击球游戏,我使用 类 创建球并使用 for 循环多次将其推入数组。

我想让球从中间向不同的方向反弹,而不是沿着相同的方向反弹。我尝试使用随机并遍历正数和负数数组(这是我被告知应该尝试的)来为我的问题编写一个解决方案,但它都遵循相同的方向并到达右下角,这是我不明白的。

这是当前发生的事情的 gif:

这是创建球时当前调用的 move() 函数:

这里还有用于循环随机数的 posRange 和 negRange 数组

let posRange = [1,2,3,4,5,7,8,9]
let negRange = [6,7,8,9,10,11,12]
move() {
        // checking if the ball is still in its start postion
        if (this.center) {
            // push the ball out with the directon (speed) that matches the range 
            this.speedX = random(posRange)
            // again with Y direction
            this.speedY = random(negRange)
            // move ball across X axis
            this.x = this.x + this.speedX;
            // move ball across Y axis
            this.y = this.y + this.speedY;
            // the ball is no longer in the center
            // reset speed variables to orginal values.
            this.speedX = this.speeds[0]
            this.speedY = this.speeds[1]
            this.center = false;

        }else if(!this.center){
            this.x = this.x + this.speedX;
            this.y = this.y + this.speedY;
        }

这可能不相关,但将包括在绘制函数期间调用的 gm_createBalls。

    function gm_activateBalls(){
        for (let i = 0; i < Balls.length; i++) {
            Balls[i].show()
            Balls[i].move()
          }
    }
    

您的 random() 函数仅初始化速度值 returns 正值。例如,您可以使用 this.speedX = random(-1, 1) 来选择 -1 和 1 之间的任何随机值,从而也允许“负”速度(即,您的一些球最初向左移动)。

使用类似这样的函数:

this.speedX *= random(-1,1)