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

HTML5 + JS: Collision Detection For Rotatable Character

本文关键字:字符 碰撞检测 旋转 JS HTML5      更新时间:2023-09-26

我正在为我的游戏开发碰撞系统;这是一个自上而下的射击游戏,角色总是静态的 - 其他一切(地图/关卡)都围绕着他移动。

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

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

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

这是我的碰撞检测(每次更新都调用):

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;
}

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

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

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

就我个人而言,我不会太担心角色碰撞。我这么说的原因很简单。

让我们看看你走在靠近一堵墙的地方。然后你转身跟随鼠标,然后角色与墙壁重叠。你现在做什么?要么你停止转弯,这会搞砸动作,要么你让精灵重叠,玩家完全卡住,直到他们再次自由。

我更喜欢使用碰撞圈。如果玩家距离墙壁的距离小于 R 像素,则将其计为碰撞并阻止玩家移动。这样,即使玩家转身,精灵也不会导致玩家卡住,他总是能够远离墙壁。

这次我进入了ludum dare 并做了一个教程来解释我的基本代码。教程可以在这里找到: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;
}

编辑

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