帆布弹跳球随机通过左边框

时间:2019-01-06 20:49:02

标签: canvas html5-canvas

我正在尝试使用随机移动的球制作画布背景。球到达边缘时会反弹。这应该很容易,但显然我错过了一些东西。

现在,前几秒钟看起来还不错,但是过了一会儿,这些球就不会打扰过左边界,而且再也不会反弹。我一直试图弄清楚几天,但失败了。任何帮助表示赞赏。

update(delta, canvas) {

    let deltaX = delta * Math.cos(this.movingDirection * Math.PI / 180);
    let deltaY = delta * Math.sin(this.movingDirection * Math.PI / 180);

    this.axisX += deltaX;
    this.axisY += deltaY;

    //set border
    if (this.axisX > (canvas.width)) {
        if (this.movingDirection > 270 && this.movingDirection < 360) {
            this.movingDirection = 180 + this.movingDirection;
        } else if (this.movingDirection < 90 && this.movingDirection > 0) {
                this.movingDirection = 180 - this.movingDirection;
        }
    }
    if (this.axisX < 0) {
        if (this.movingDirection > 180 && this.movingDirection < 270) {
            this.movingDirection = 540 - this.movingDirection;
        } else if (this.movingDirection <= 180 && this.movingDirection > 90) {
            this.movingDirection = 180 - this.movingDirection;
        }
    }

    if (this.axisY > (canvas.height) || this.axisY < 0) {
        if (this.movingDirection > 180 ) {
            this.movingDirection = 360 - this.movingDirection;
        } else if (this.movingDirection <= 180) {
            this.movingDirection = 360 - this.movingDirection;
        }
    }
    this.draw();
}

this.movi​​ngDirection是一个介于0到360之间的随机生成的数字。

这是一个完整的示例https://jsfiddle.net/calmdown/qr89b034/1/

谢谢!

1 个答案:

答案 0 :(得分:1)

由于您的方法不在那儿(很复杂),所以我不会尝试找出代码的问题

相反,您可以使用增量x和y进行墙反弹,然后从中计算新方向。

以下update函数将解决您的问题。

update(delta, canvas) {
    var dx, dy,x,y;
    dx = delta * Math.cos(this.movingDirection * Math.PI / 180);
    dy = delta * Math.sin(this.movingDirection * Math.PI / 180);
    x = this.axisX += dx;
    y = this.axisY += dy;
    const r = this.radius;


    if(dx > 0) { // moving to the right
        if(x + r >= canvas.width) {
            x = canvas.width - r;
            dx = -dx;
        }    
    }else if(dx < 0) { // moving to the left
        if(x - r <= 0) {
            x = r;
            dx = -dx;
        }       
    }
    if(dy > 0) { // moving down
        if(y + r >= canvas.height) {
            y = canvas.height - r;
            dy = -dy;
        }        
    }else if(dy < 0) { // moving up
        if(y - r <= 0) {
            y = r;
            dy = -dy;
        }           
    }

    this.axisX = x;
    this.axisY = y;
    this.movingDirection = Math.atan2(dy, dx) * (180 / Math.PI);

    this.draw();
}