การกระเด็น Google

กล่องสีแดงนี้จะกระเด็นขึ้นเมื่อตกลงมาถึงพื้น:


การกระเด็น

ความสามารถที่เราจะเพิ่มเติมคือ 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 ดินแดนต่ำที่สุด = this.gamearea.canvas.height - this.height;
    if (this.y > ดินแดนต่ำที่สุด) {
      this.y = ดินแดนต่ำที่สุด;
      this.gravitySpeed = -(this.gravitySpeed * this.bounce);
    }
  }
}

ทดลองด้วยตัวเอง