Spelbeweging
Met de nieuwe manier om componenten te tekenen, uitgelegd in het hoofdstuk Spelrotatie, zijn de bewegingen flexibeler.
Hoe objecten te verplaatsen?
Voeg een speed
eigenschap toe aan de component
constructor, die de huidige snelheid van het onderdeel vertegenwoordigt.
Breng ook enkele wijzigingen aan in de newPos()
methode om de positie van het onderdeel te berekenen op basis van speed
en angle
.
Standaard zijn de componenten naar boven gericht en door de snelheidseigenschap in te stellen op 1, begint de component vooruit te gaan.
Voorbeeld
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);
}
}
Bochten maken
We willen ook links en rechts kunnen draaien. Maak een nieuwe eigenschap met de naam moveAngle
, die de huidige verplaatsingswaarde of rotatiehoek aangeeft. newPos()
Bereken
in de methode op angle
basis van de moveAngle
eigenschap:
Voorbeeld
Stel de eigenschap moveangle in op 1, en kijk wat er gebeurt:
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);
}
}
Gebruik het toetsenbord
Hoe beweegt het rode vierkant bij gebruik van het toetsenbord? In plaats van op en neer en van links naar rechts te bewegen, beweegt het rode vierkant naar voren als je de "omhoog"-pijl gebruikt, en draait het naar links en rechts als je op de linker- en rechterpijl drukt.