W3C中文教程
全球最大最新的中文 Web 技术教程
HTML CSS SQL PHP COLORS MYSQL BOOTSTRAP
 

HTML 游戏弹跳



当这个红色方块击中地板时,它会弹起:




弹跳

我们要添加的另一个功能是 bounce 属性。

bounce 属性表示当重力使其跌落到地面时,组件将反弹。

bounce 属性值必须是数字。0根本没有反弹,1将使组件一直反弹到它开始下降的位置。

Example

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);
        }
    }
}
尝试一下 »