HTML5 + JS:可旋转字符的碰撞检测

Oli*_*nes 8 javascript html5 transform rotation collision

我正在为我的游戏制作碰撞系统; 这是一个自上而下的射手,角色永远是静态的 - 其他一切(地图/水平),在他周围移动.

角色也会旋转,因此它始终面向鼠标位置.

考虑到这一点,我似乎无法理解我的碰撞系统,它需要考虑角色旋转,对吧?

我基本上只想检查给定的对象是否完全'触摸'我的角色/精灵.我不太确定我使用的数学是否正确.

这是我的碰撞检测(称为每次更新):

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;

}
Run Code Online (Sandbox Code Playgroud)

此外,不确定这是否相关,但这是用于移动我的地图画布的变换:

ctxMap.setTransform(1, 0, 0, 1, -Map.x + gameWidth/2, -Map.y + gameHeight/2);
Run Code Online (Sandbox Code Playgroud)

如果有人帮助我在这里,我将非常感激:)谢谢!

PJe*_*fes 2

这次我进入了ludumdar并做了一个教程来解释我的基本代码。教程可以在这里找到:http://www.philjeffes.co.uk/wordpress/ ?p=63

这演示了基于圆的碰撞检测的示例 - 请随意使用任何代码。以下代码是该代码的改编版,用于一般用途:

function CollisionCheck(obj1,obj2){
    // If the two objects are less the sum of their collision radii apart then they have collided
    // Note that one obj is obj (with a loc and a size) and the other is this.
    // Returns true if the objects are touching

    var dist = obj2.size + obj1.size; // The distance they must be apart to be not touching
    if(obj1.x-obj2.x>dist || obj1.x-obj2.x<-dist)
       return false; // Too far apart in x plane
    if(obj1.y-obj2.y>dist || obj1.y-obj2.y<-dist)
       return false; // Too far apart in y plane

    var xDist = obj1.x-obj2.x;
    var yDist = obj1.y-obj2.y;

   var hyp = Math.sqrt((xDist*xDist)+(yDist*yDist));

   if(hyp<dist)
    return true;

   return false;

}
Run Code Online (Sandbox Code Playgroud)

编辑

删除了评论中 vals 指出的 Math.abs 调用。