2014-12-04 64 views
1

我想做一个算法来处理两个包围盒(我的播放器和一些固体对象)之间的碰撞,而不使用sf :: Rect与SFML提供的相交。现在,我这是怎么检测实际碰撞:包围盒碰撞检测算法

if (obstacle.GetPosition().x < p.getPlayerPosition().x + p.getPlayerSize().x && 
    obstacle.GetPosition().x + obstacle.GetSize().x > p.getPlayerPosition().x && 
    obstacle.GetPosition().y < p.getPlayerPosition().y + p.getPlayerSize().x && 
    obstacle.GetSize().y + obstacle.GetPosition().y > p.getPlayerPosition().y) 
{ 
    // Collision 
} 

不过,我还需要弄清楚其上的障碍四边玩家碰撞,这样我就可以设置正确的玩家位置。有没有人有任何想法如何做到这一点尽可能简单和有效?

回答

0

这不是最好的,但它可能会帮助你。
我有两个箱子命名box1box2

var dx = box1.x - box2.x; 
    var px = (box2.xw + box1.xw) - Math.abs(dx);//penetration depth in x 

    if(0<px){ 
     var dy = box1.y - box2.y; 
     var py = (box2.yw + box1.yw) - Math.abs(dy);//penetration depth in y 

     if(0<py){ 

      // Collision detected 

      if(px < py){ 
       //project in x 
       if(dx < 0){ 
        //project to the left 
        px *= -1; 
        py *= 0; 
       } 
       else{ 
        //proj to right 
        py = 0; 
       } 
      } 
      else{    
       //project in y 
       if(dy < 0){ 
        //project up 
        px = 0; 
        py *= -1; 
       } 
       else{ 
        //project down 
        px = 0; 
       } 
      } 
      // we get px and py , penetration vector 

      box1.x += px; 
      box1.y += py; 
     } 
    } 

这里以JavaScript

Example