Canvas Game: Maximum steering angle in n seconds

384 Views Asked by At

So I have no idea if the heading brings my problem to a point and my english might not be that good to explain it entirely. Luckily the code can :D

So, I'm working on a that little multiplayer game where you can steer a line with the keyboard (speed is e.g. 300 pixel per second and you adjust it's moving angle with the keys).

Each player draws an infinite line and when your 'snake' .. idk how you would call it .. hits something else than black (background color) you are dead. The player who lives longest wins.

You can collect items and one of this items is a 'Hadouken' from Streetfighter which targets the nearest player and tries to hit him (Same here: speed and angle given).

The 'Hadouken'-angle is calculated every frame. aimTo is the player:

if (hadouken.aimTo)
{
    var dx = hadouken.aimTo.x - hadouken.x;
    var dy = hadouken.aimTo.y - hadouken.y;
    var dist = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));

    hadouken.rad = Math.atan2(dy, dx);

    if (dist < hadouken.aimTo.radius)
    {
        ...
    }
}

var plusX = hadouken.speed * _.timeFactor * Math.cos(hadouken.rad);
var plusY = hadouken.speed * _.timeFactor * Math.sin(hadouken.rad);

hadouken.x += plusX;
hadouken.y += plusY;

_.rotateDraw(hadouken, hadouken.x - hadoukenWidth / 2, hadouken.y - hadoukenHeight / 2, hadoukenWidth, hadoukenHeight, {rad: hadouken.rad}, function(x, y) {
    _.drawImage(hadoukenImage, x, y, hadoukenWidth, hadoukenHeight);
});

But this thing always has the right angle and will reach it's target (speed = targetSpeed * 1.5 ;)) if it soesn't vanish after the hardcoded 5 seconds. You have no chance do dodge it with your line. I'ts curves are just too sharp.

My question is: Can you, somehow, limit the increase of the angle to .. idk .. 30 degrees per second ? I'm sure I could do that on my own but that would be fancy and probably unnecessarily dificult.

I hope that was clear enough, sorry again for my english and I hope to get some answers :)

1

There are 1 best solutions below

14
On

Instead of

hadouken.rad = Math.atan2(dy, dx);

I'd code it that way:

// time_elapsed is time since previous animation state update (in time units)
// angular_speed is max turning speed in radians per time unit

var dest_angle = Math.atan2(dy, dx);

// normalize destination vector dx,dy
var nx = Math.cos(dest_angle);
var ny = Math.sin(dest_angle);

// calc current vector
var cx = Math.cos(hadouken.rad);
var cy = Math.sin(hadouken.rad);

// calc cross product, its sign will tell ya which direction we should turn
var crp = cx*ny - cy*nx;

var ang_ofs = angular_speed * time_elapsed;

if ( crp>0 ) // shoud turn clockwise
    hadouken.rad += ang_ofs;
else
if ( crp<0 )  // shoud turn counter clockwise
    hadouken.rad -= ang_ofs;

// dont let it over-turn
cx = Math.cos(hadouken.rad);
cy = Math.sin(hadouken.rad);
var crp2 = cx*ny - cy*nx;
if (crp*crp2<0) // sign changed!
    hadouken.rad = dest_angle;