游戏弹跳
这个红色的正方形在碰到地面时会弹跳
弹跳
我们想要添加的另一个功能是 bounce
属性。
bounce
属性指示组件在重力使其落到地面时是否会弹回。
弹跳属性的值必须是一个数字。0 表示没有弹跳,1 表示组件会弹回到开始下落的位置。
示例
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.1;
this.gravitySpeed = 0;
this.bounce = 0.6;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = this.gamearea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = -(this.gravitySpeed * this.bounce);
}
}
}
自己试试 »