Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 + JS: Collision Detection For Rotatable Character

I'm working on the Collision system for my game; which is a top down shooter, the character is always static - and everything else (Map/Level), moves around him.

The character also rotates so it's always facing the mouse position.

With that in mind, I can't seem to get my head around my collision system, which needs to take into account of the character rotation, right?

I basically just want to check if the given object is at all 'touching' my character/sprite. I'm not so sure if the maths I'm using is correct.

This is my collision detection (called every update):

function detectCollisions(){

    //Detect for game props
    if(collides(Map, TestProp)){
        console.debug("Touching...");
    }

}

function collides(a, b){

    //ctxMap.setTransform(1, 0, 0, 1, -Map.x + gameWidth/2, -Map.y + gameHeight/2);

    //var transX = -Map.x + gameWidth/2;
    //var transY = -Map.y + gameHeight/2;

    //need to take player rotation into account too!

    //console.debug(a.x + " " + b.x + " " + b.width + " " + Player.width); //A Width

    /*return  a.x < b.x + b.width && a.x + Player.width > b.x &&
            a.y < b.y + b.height && a.y + Player.height > b.y;*/

    var xOffset = Math.cos(Player.characterRotation); //+ Player.width;
    var yOffset = Math.sin(Player.characterRotation); //+ Player.height;

    return  Map.x + xOffset > b.x && Map.x + xOffset < b.x + b.width &&
            Map.y + yOffset > b.y && Map.y + yOffset < b.y + b.height;

}

Also, not sure if this is relevant, but this is the transform used to move my Map Canvas:

ctxMap.setTransform(1, 0, 0, 1, -Map.x + gameWidth/2, -Map.y + gameHeight/2);

Would much appreciate it if someone helped me out here :) Thanks!

like image 678
Oliver Jones Avatar asked Jan 24 '13 20:01

Oliver Jones


1 Answers

Personally, I wouldn't worry so much about the character colliding. The reason I say that is simple.

Let's saw you're walking real close to a wall. Then you turn to follow the mouse, and the sprite then overlaps the wall. What do you do now? Either you stop the turning, which would screw up movements, or you let the sprite overlap and the player gets completely stuck until they turn free again.

My preference would be to use a collision circle. If the player is closer than R pixels from the wall, count it as a collision and stop the player from moving. This way, even if the player turns, the sprite will never cause the player to get stuck and he will always be able to move away from the wall.

like image 97
Niet the Dark Absol Avatar answered Nov 07 '22 23:11

Niet the Dark Absol