我正在尝试使球从右向左无限弹跳,但我无法使其正常工作。下面的代码使该球将向右再向左移动,但我无法使其再次向右弹回。有人有任何解决办法?

var speed = 3;
var ball = {
x: 100,
y: 200,

draw: function() {
    fill('red');
    circle(this.x, this.y, 100);
},
move: function(){
    if(this.x > width){
        speed = -3;
    }
    this.x = this.x + speed;
}
}

function setup() {
    createCanvas(500, 500);
    background(200, 225, 200);
}

function draw() {
    background(200,225,200);
    ball.draw();
    ball.move();

    }


附言这是我的第一篇文章,请告诉我是否做错了什么或需要添加任何内容。

最佳答案

如果球击中右侧(speed *= -1)或击中左侧(this.x > width),则必须反转运动方向(this.x < 0):

let radius = 50;
if (this.x > width-radius  || this.x < radius ) {
    speed *= -1;
}


参见示例:



var speed = 3;
var ball = {
  x: 100,
  y: 200,
  radius: 50,

  draw: function() {
      fill('red');
      circle(this.x, this.y, this.radius*2);
  },
  move: function(){
      if (this.x > width-this.radius || this.x < this.radius) {
          speed *= -1;
      }
      this.x = this.x + speed;
  }
}

function setup() {
    createCanvas(500, 500);
    background(200, 225, 200);
}

function draw() {
    background(200,225,200);
    ball.draw();
    ball.move();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

关于javascript - P5-左右左右弹跳球,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59646011/

10-08 23:39