检测是否接触到身体LibGDX

时间:2018-07-09 06:56:18

标签: java android libgdx

我正在尝试查看触摸位置是否与主体碰撞,我不确定实现它的最佳方法。

到目前为止,我有一个Obstacle.java,它将多边形形的主体绘制为矩形。在世界上绘制效果很好,我只需要检查碰撞即可。

此外,我想在此物体上添加一些Sprite / Texture / Image,所以最好检查一下Sprite之间的碰撞,而不是物体。因此,任何指向正确方向的指针都将有所帮助。

Obstacle.java

public class Obstacle{
    public int x,y;
    public Vector3 position;
    public World world;

    private Body body;
    private BodyDef bodyDef;
    private PolygonShape shape;

    private float density = 1f;
    private final float width = 360f;
    private final float height = 20f;

    Random r;

    public Obstacle(World world) {
        r = new Random();

        this.world = world;

        //rectangle
        bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.position.set( new Vector2( x + width / 2, y + height / 2));

        float randomValue = (float)(0 + (540 - 0) * r.nextDouble());

        shape = new PolygonShape();
        shape.setAsBox( width / 2, height / 2 );

        body = world.createBody(bodyDef);
        body.createFixture(shape, density);
        body.setTransform(randomValue,1160,0);

        float angularVelocity;
        if(r.nextInt(2)==0){
            angularVelocity=-3;
        }else{
            angularVelocity=3;
        }

        body.setAngularVelocity(angularVelocity);
        body.setLinearVelocity(0,-250);

    }

    public float getX() {
        return position.x;
    }
    public float getY() {
        return position.y;
    }

    public float getWidth() {
        return 360 / GdxGame.PPM;
    }

    public float getHeight() {
        return 20 / GdxGame.PPM;
    }

    public void render(SpriteBatch batch,float delta) {
    }

    public Boolean collidesWithPlayer(float touchX, float touchY){
        return false;
    }

}

最后一种方法 collidesWithPlayer 是我为实施检测而付出的努力,在Screen.java中,我有:

 for(int i = 0; i < obstacles.size(); i++) {
     if(obstacles.get(i).collidesWithPlayer(pointerX, pointerY)) {
         hasDied=true;
     }else{
         isPaused=true;
     }
  }

0 个答案:

没有答案