2014-04-01 82 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

然後你以錯誤的方式使用它 –