游戲彈跳
這個紅色方塊落地時會彈起:
彈跳
我們要添加的另一個功能是 bounce
屬性。
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); } } }