2013-03-29 37 views
2

我在jquery/javascript中製作遊戲。遊戲將通過使用鼠標點擊屏幕來擊中一個移動物體。我有檢測位問題。是否有一個jQuery/JavaScript函數可以隨時測量兩個對象中心之間的距離?因此,我可以輕鬆地控制兩個中心的距離。如果碰撞。他們都是兩個圈子。如何測量兩個圓之間的距離,然後檢查碰撞?

<div id="box"> 
     <div id="prepend"> 
      <div id="hero"></div> 
     </div> 

     <div id="enemy"></div> 
</div> 

「box」是遊戲發生的區域,「hero」是你要擊中「敵人」的子彈。

+0

我應該說,我已經嘗試了jquerycollision插件,但它沒有奏效。 – user1859736

+0

你的意思是'Math.sqrt(Math.pow(xdist,2)+ Math.pow(ydist,2))'? –

+0

不要重新發明輪子:http://stackoverflow.com/questions/773717/please-recommend-a-jquery-plugin-that-handles-collision-detection-for-draggable – DhruvPathak

回答

0

您可以使用以下方法:

var $this = $(this); 
var offset = $this.offset(); 
var width = $this.width(); 
var height = $this.height(); 

var centerX = offset.left + width/2; 
var centerY = offset.top + height/2; 

這樣做對雙方,然後計算這些值之間的差異。

0

沒有一個,但它很簡單實際上:

  1. 獲取當前項的絕對COORDS以及寬度和高度
  2. 計算中心的點(x +寬/ 2,Y +高度/ 2)
  3. 做到這一點對兩個圓
  4. 使用三角函數這兩個點之間計算距離:x的差平方加在正方形Y的差,利用這一平方根=距離
  5. 如果距離減去兩個圓的半徑大於0,則不發生碰撞。如果0:他們碰觸,如果小於0,他們碰撞。
5

要獲得的距離用公式enter image description here

function getDistance(obj1,obj2){ 
    Obj1Center=[obj1.offset().left+obj1.width()/2,obj1.offset().top+obj1.height()/2]; 
    Obj2Center=[obj2.offset().left+obj2.width()/2,obj2.offset().top+obj2.height()/2]; 

    var distance=Math.sqrt(Math.pow(Obj2Center[0]-Obj1Center[0], 2) + Math.pow(Obj2Center[1]-Obj1Center[1], 2)) 

    return distance; 
} 

呼叫使用

getDistance($("#obj1"),$("#obj2")); 

要檢查碰撞:

function hasCollision(obj1,obj2){  
    return getDistance(obj1,obj2)<obj1.width()/2+obj2.width()/2; 
} 

這裏有一個jsfiddle example證明兩者