簡體   English   中英

p5.js 讓球從中間移出並分成不同的方向

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

我正在制作一個名為 popThatBall 的簡單點擊球游戲,我使用類來創建球並使用 for 循環將其多次推送到數組中。

我想讓球從中間向不同的方向反彈,而不是沿着相同的方向。 我嘗試使用隨機數和迭代正數和負數數組(我被告知我應該嘗試)來編寫我的問題的解決方案,但它都遵循相同的方向並轉到右下角,這是我不明白的。

這是當前正在發生的事情的 GIF:

球移動和不工作

這是創建球時當前調用的 move() function:

這里還有用於循環隨機數的 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;
        }

這可能不相關,但將包括在抽獎 function 期間調用的 gm_createBalls。

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

您用於初始化速度值的random() function 僅返回正值。 例如,您可以使用this.speedX = random(-1, 1)選擇 -1 和 1 之間的任何隨機值,因此也允許“負”速度(即,您的一些球最初向左移動) .

使用與此類似的 function:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM