P5 - 从左到右再向后弹跳球
P5 - bouncing ball from left to right and back
我试图让球从右向左无限弹跳,但我无法让它工作。下面的代码使球会向右移动,然后向左移动,但我无法让它再次向右反弹。有人知道如何解决这个问题吗?
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();
}
P.S。这是我的第一个 post 如果我做错了什么或需要添加任何内容,请告诉我。
如果球击中右侧(this.x > width
)或击中左侧(this.x < 0
),则必须反转运动方向(speed *= -1
):
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>
我试图让球从右向左无限弹跳,但我无法让它工作。下面的代码使球会向右移动,然后向左移动,但我无法让它再次向右反弹。有人知道如何解决这个问题吗?
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();
}
P.S。这是我的第一个 post 如果我做错了什么或需要添加任何内容,请告诉我。
如果球击中右侧(this.x > width
)或击中左侧(this.x < 0
),则必须反转运动方向(speed *= -1
):
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>