2014-04-01 88 views
0

这里是我工作至今的jsfiddle:http://jsfiddle.net/TLYZS/碰撞检测算法问题

如果你调试代码,并检查冲突功能,你可以看到,碰撞工作正常时,与其他角色的用户重叠希望在格斗游戏中的碰撞不应该像这样工作:

  1. 你可以看到,当我冲或从一个小的距离一脚角色冲突检测功能不能使用,即使你能看到它在屏幕上工作该用户正在惩罚该字符
  2. 我如何修复这个碰撞检测功能,使其工作正常?

    function Collision(r1, r2) { 
         return !(r1.x > r2.x + r2.w || r1.x + r1.w < r2.x || r1.y > r2.y + r2.h || r1.y + r1.h < r2.y); 
        } 
    

enter image description here

enter image description here

回答

0

这里是我的老JS实现flash.geom.Rectangle的。试着在你的项目中使用它:

function Rectangle(x, y, w, h) 
{ 
    if(!x) x = 0; if(!y) y = 0; if(!w) w = 0; if(!h) h = 0; 
    this.x = x;  this.y = y; 
    this.width = w; this.height = h;  
} 
Rectangle.prototype.isEmpty = function() // : Boolean 
{ 
    return (this.width<=0 || this.height <= 0); 
} 
Rectangle.prototype.intersection = function(rec) 
{ 
    var l = Math.max(this.x, rec.x); 
    var u = Math.max(this.y, rec.y); 
    var r = Math.min(this.x+this.width , rec.x+rec.width); 
    var d = Math.min(this.y+this.height, rec.y+rec.height); 
    if(r<l || d<u) return new Rectangle(); 
    else return new Rectangle(l, u, r-l, d-u); 
} 

然后你只需要调用

if(!r1.intersection(r2).isEmpty()) ... // there is a collision 
+0

如果(R 返回false? else return new Rectangle(l,u,r-l,d-u) - > return true? 我试过你的代码,但它给了我相同的结果 – Sora

+0

然后你以错误的方式使用它 –