当这个形状从左向右移动时,我常常使用两种方法将形状返回到画布,这些方法使用 if / else 语句并使用模数
例如(使用JavaScript):
function Shape(size, movement){
this.size = size;
this.pos_x = Math.random()*500;
this.pos_y = Math.random()*500;
this.movement = movement;
};
var shape1 = new Shape(5, 2);
var shape2 = new Shape(5, 4);
// first way to move a shape from left to right and return it to the canvas.
if(shape1.pos_x < canvas.width){
shape1.pos_x += shape1.movement;
}else {shape1.pos_x = 0;};
// second way is using modulus.
shape2.pos_x = (shape2.pos_x + shape2.movement)% canvas.width;
现在,如果形状在相反的方向上移动,即从右到左,我可以使用第一种方式使用 if / else 语句,如下所示:
var shape3 = new Shape(5, 2);
var shape4 = new Shape(5, 4);
// first way to move a shape from right to left and return it to the canvas
if(shape3.pos_x > 0){
shape3.pos_x -= shape3.movement;
}else {shape3.pos_x = canvas.width;};
我的问题是我们如何使用模数来获得shape4的相同行为。
提前致谢。