我正在使用JS将一个矩形动画化在一个canvas元素上。当矩形到达canvas的宽度时,我想改变动画方向,但无法确定逻辑,因为它只转一次,然后又向右移动,实际上粘在了canvas的宽度上。
请查看下面的代码以更清晰地理解:
请查看下面的代码以更清晰地理解:
function startGame() {
game.start();
game.createSquare('red', 100, 10, 10, 10);
}
function updateGame() {
game.clear();
//lines below are causing issues
if(game.x < game.canvas.width){
game.x++;
} else {
game.x--;
}
game.update();
}
var game = {
//create the canvas element
canvas: document.createElement('canvas'),
//set up the canvas
start: function () {
this.context = this.canvas.getContext('2d');
this.canvas.height = 400;
this.canvas.width = 400;
document.body.insertBefore(this.canvas ,document.body.childNodes[0]);
},
//clear the canvas
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
//create Square
createSquare: function(color, height, width, x, y) {
this.height = height;
this.width = width;
this.color = color;
this.x = x;
this.y = y;
this.update = function(){
this.context.fillStyle = this.color;
this.context.fillRect(this.x , this.y , this.width, this.height);
}
}
}
startGame();
setInterval(updateGame,50);
game.x < game.canvas.width
为false时,你需要反转速度。而且每次都要执行game.x += velocity
操作。 - Pierre C.