Oyun Hareketi
Oyun Döndürme bölümünde açıklanan yeni bileşen çizim yöntemi ile hareketler daha esnektir.
Nesneler Nasıl Taşınır?
Bileşenin geçerli hızını temsil eden yapıcıya bir speed
özellik ekleyin .component
newPos()
Ayrıca , bileşenin konumunu hesaplamak için yöntemde ve bazında speed
bazı değişiklikler yapın angle
.
Varsayılan olarak, bileşenler yukarı bakar ve hız özelliği 1 olarak ayarlandığında bileşen ilerlemeye başlar.
Örnek
function component(width, height, color, x, y) {
this.gamearea = gamearea;
this.width = width;
this.height = height;
this.angle = 0;
this.speed = 1;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
dönüşler yapmak
Ayrıca sağa ve sola dönüş yapabilmek istiyoruz. moveAngle
Geçerli hareket eden değeri veya dönüş açısını gösteren adlı yeni bir özellik yapın . Yöntemde , özelliğe dayalı olarak newPos()
hesaplayın
:angle
moveAngle
Örnek
Moveangle özelliğini 1 olarak ayarlayın ve ne olduğunu görün:
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.angle = 0;
this.moveAngle = 1;
this.speed = 1;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
Klavyeyi Kullan
Klavyeyi kullanırken kırmızı kare nasıl hareket eder? Yukarı ve aşağı ve bir yandan diğer yana hareket etmek yerine, "yukarı" oku kullandığınızda kırmızı kare ileriye doğru hareket eder ve sol ve sağ oklara bastığınızda sola ve sağa döner.