Oyun Yerçekimi
Bazı oyunlar, yerçekiminin nesneleri yere çekmesi gibi, oyun bileşenini bir yönde çeken kuvvetlere sahiptir.
Yer çekimi
Bu işlevi bileşen kurucumuza eklemek için gravity
önce mevcut yerçekimini ayarlayan bir özellik ekleyin. Ardından gravitySpeed
, çerçeveyi her güncellediğimizde artan bir özellik ekleyin:
Örnek
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.05;
this.gravitySpeed = 0;
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;
}
}
Dibe vur
Kırmızı karenin sonsuza kadar düşmesini önlemek için, oyun alanının dibine çarptığında düşmeyi durdurun:
Örnek
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
}
}
Hızlanma
Bir oyunda, sizi aşağı çeken bir kuvvete sahip olduğunuzda, bileşeni hızlandırmak için bir yönteminiz olmalıdır.
Birisi bir düğmeye tıkladığında bir işlevi tetikleyin ve kırmızı karenin havada uçmasını sağlayın:
Örnek
<script>function accelerate(n) {
myGamePiece.gravity = n;
}</script>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">ACCELERATE</button>
Bir oyun
Şimdiye kadar öğrendiklerimize dayanarak bir oyun yapın: