I am creating a mini space ship game with a feel similar to escape velocity. I cannot seem to get inertia to work correctly.
I am also having problems with the turning functions. If I tap the left or right arrow keys then it does not follow anything similar to the circular type movement that should be happening.
$(function() {
var canvas = Raphael('game', 1000, 800);
var background = canvas.rect(0, 0, 1000, 800);
background.attr("fill", "black");
var ship = canvas.rect(200, 200, 10, 35);
ship.attr("fill", "red");
ship.angle = 0;
ship.turnrate = 4;
ship.maxSpeed = 2;
ship.acc = 0;
ship.accSpeed = 0.25;
ship.vel = [0,0];
var up = 0;
var left = 0;
var right = 0;
var speedx = 0;
var speedy = 0;
function moveShip() {
if (left == 1) {
ship.angle = (ship.angle - ship.turnrate) % 360;
}
if (right == 1) {
ship.angle = (ship.angle + ship.turnrate) % 360;
}
if (up == 1) {
if (ship.acc < ship.maxSpeed) {
ship.acc += ship.accSpeed;
}
if (ship.acc > ship.maxSpeed) {
ship.acc = ship.speed;
}
}
if (up == 0) {
if (ship.acc > 0) {
ship.acc -= ship.accSpeed;
}
if (ship.acc < 0) {
ship.acc = 0;
}
}
speedx = ship.vel[0] + ship.acc * Math.sin(ship.angle);
speedy = ship.vel[1] + ship.acc * Math.cos(ship.angle);
ship.vel = [speedx, speedy];
ship.transform("");
ship.rotate(ship.angle);
ship.attr({x: ship.vel[0], y: ship.vel[1]});
$("#stats").text("ship.angle: " + ship.angle
+ " vel[0]: " + ship.vel[0] + " vel[1]: " + ship.vel[1]
+ " ship.speed: " + ship.maxSpeed + " speedx: " + speedx + " speedy: " + speedy);
}
function keyPressed(evt) {
if (evt.keyCode == 38) {
up = 1;
}
if (evt.keyCode == 37) {
left = 1;
}
if (evt.keyCode == 39) {
right = 1;
}
}
function keyReleased(evt) {
if (evt.keyCode == 38) {
up = 0;
}
if (evt.keyCode == 37) {
left = 0;
}
if (evt.keyCode == 39) {
right = 0;
}
}
function gameloop() {
moveShip();
}
$(document).keydown(keyPressed);
$(document).keyup(keyReleased);
setInterval(gameloop, 30);
});
I have been searching stack overflow and the internet, but most questions out there are to do with the classic Space Invaders type game which does not involve turning or inertia.
Any help would be appreciated, I really just want to have a good understanding of what I am missing.
Are you sure you want to change the acceleration of a ship with the arrow keys? Remember, acceleration is the rate of change of the velocity. This means, if you have a constant acceleration then you velocity will start to grow and grow and grow. Pretty soon you will have a ship that is going way too fast.
The results from the chatroom, here for posterity:
There were two bugs fixed. A
posattribute was added, so that velocity and position can be updated separately. Also,Math.sinandMath.costake angles in radians, so we converted the angle for those functions.You can play with the results: http://jsfiddle.net/mJcN7/8/