2017-09-26 47 views
0

我对libgdx和游戏开发非常陌生。我被赋予了一个任务,在这个任务中我得到了一个非常简单的2D游戏,它已经实现了矩形碰撞检测。libgdx像素碰撞非常简单的2D游戏

游戏只是由一个可以由玩家控制的广场组成,该广场位于墙内,墙内有其他分散的广场。我现在需要在玩家广场和分散的广场/墙壁之间实现像素完美的碰撞。

我最初尝试使用Pixmap,并试图检查当前坐标的像素是否对玩家矩形是透明的,以及与它碰撞的任何矩形是否透明,但是无法正确执行代码。

据我所知,我必须检查两个对象在某个坐标上的像素颜色,看看它们是否对发生碰撞都不透明,但我遇到了麻烦。我花了很长时间研究和在网上寻找,所以如何执行这个任何帮助或建议将不胜感激!

public boolean entityCollision(Entity e1, Direction direction, float newX, float newY) { 
    boolean collision = false; 

    for(int i = 0; i < entities.size(); i++) { 
     Entity e2 = entities.get(i); 

     if (e1 != e2) { 

      if (newX < e2.x + e2.width && e2.x < newX + e1.width && 
       newY < e2.y + e2.height && e2.y < newY + e1.height) { 
       collision = true; 

       int colorOne = player.getPixel((int)newX,(int)newY); 
       int colorTwo = enemy.getPixel((int)e2.x,(int)e2.y); 

       if (colorOne != 0 && colorTwo != 0) { 
        collision = true; 
        e1.entityCollision(e2, newX, newY, direction); 
       } 
      } 
     } 
    } 

    return collision; 
} 

回答

1

看看libgdx的the Rectangle implementation。它允许你做这样的事情:

Rectangle e1Rec = new Rectangle(e1.x, e1.y, e1.width, e1.height); 
Rectangle e2Rec = new Rectangle(e2.x, e2.y, e2.width, e2.height); 

if (e1Rec.contains(e2Rec)) { 
    // Collision! 
} 
+0

谢谢!我能够使用.overlaps()方法而不是.contains()来工作。 –

0

如果你想与一个精灵的碰撞,你得到的精灵矩形,并检查该矩形的内部冲突。

sprite.getboundingrectangle().contains(x, y) ; //returns a boolean