如何找到我使用LibGDX点击的形状?

时间:2015-01-27 12:57:54

标签: java libgdx

注意:这些形状是具有透明度的PNG。 如何找到我点击哪种形状?

enter image description here

class Component extends Actor {

    private Pixmap pixmap;
    private Texture texture;

    public Component(String name, FileHandle file) {
        this.pixmap = new Pixmap(file);
        this.texture = new Texture(pixmap);
        setName(name);
        setBounds(0, 0, texture.getWidth(), texture.getHeight());
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(texture, getX(), getY());
    }

    public Pixmap getPixmap() {
        return pixmap;
    }       
}

** 公共类Shapes扩展ApplicationAdapter实现InputProcessor ... **

public void create() {
    stage = new Stage(new ScreenViewport());
    Group group = new Group();

    Component cpn01 = new Component("01", Gdx.files.internal("01.png"));
    Component cpn02 = new Component("02", Gdx.files.internal("02.png"));
    Component cpn03 = new Component("03", Gdx.files.internal("03.png"));

    cpnBlue.setPosition(100f, 50f);
    cpnRed.setPosition(150f, 70f);
    cpnGreen.setPosition(175f, 100f);

    group.addActor(cpn01);
    group.addActor(cpn02);
    group.addActor(cpn03);

    stage.addActor(group);

    Gdx.input.setInputProcessor(this);
}

public boolean touchDown(int screenX, int screenY, int pointer, int button) {

    Group group = (Group) stage.getActors().first();

    for (int i = 0; i < group.getChildren().size; i++) {
        Component c = (Component) group.getChildren().get(i);

        Vector2 vc = c.screenToLocalCoordinates(new Vector2((float) screenX, (float) screenY));
        Pixmap pix = c.getPixmap();

        int pixel = pix.getPixel((int) vc.x, (int) vc.y);
        int transparency = ((pixel & 0xff000000) >> 24);

        if ((pixel & 0x000000ff) != 0) {
            Gdx.app.log("HIT", c.getName() + ", " + pixel + ", " + transparency);
            break;
        }

    }

    return false;
}

我想只选择形状,忽略PNG的透明像素。

1 个答案:

答案 0 :(得分:0)

您可以使用鼠标位置使用Pixmap的getPixel方法。

int val = pixmap.getPixel(x, y);

然后您可以从结果中提取RGBA值

Color.rgba8888ToColor(color, val);
int R = (int)(color.r * 255f);
int G = (int)(color.g * 255f);
int B = (int)(color.b * 255f);
int A = (int)(color.a * 255f);

如果alpha值大于0,您可以检查点击了哪种颜色。