0
我有一個帶有精靈的矩形,我必須檢測觸摸位置是否位於矩形內。無法檢測是否在libgdx中觸摸了矩形
這是我的代碼,
if (Gdx.input.isTouched())
{
int x1 = Gdx.input.getX();
int y1 = Gdx.input.getY();
Vector3 inputs = new Vector3(x1, y1, 0);
gamecam.unproject(inputs);
Gdx.app.log("x" + inputs.x, "y" + inputs.y);
Gdx.app.log("rect" + rectangle.x, "rect" + rectangle.y);
if(rectangle.contains(inputs.x,inputs.y))
{
Gdx.app.log("x" + inputs.x, "y" + inputs.y);
Gdx.app.log("rect" + rectangle, "rect" + rectangle.y);
}
}
矩形定義,
BodyDef bdef = new BodyDef();
bdef.type = BodyDef.BodyType.StaticBody;
b2body = screen.getWorld().createBody(bdef);
rectangle = new Rectangle();
rectangle.setHeight(55);
rectangle.setWidth(55);
PolygonShape head = new PolygonShape();
rectangle.setX(300);
rectangle.setY(10);
bdef.position.set((rectangle.getX() - rectangle.getWidth()/2)/MyJungleGame.PPM, (rectangle.getY() - rectangle.getHeight()/2)/MyJungleGame.PPM);
head.setAsBox(rectangle.getWidth()/2/MyJungleGame.PPM, rectangle.getHeight()/2/MyJungleGame.PPM);
FixtureDef fdef = new FixtureDef();
fdef.shape = head;
setPosition(b2body.getPosition().x - getWidth()/2, b2body.getPosition().y - getHeight()/2);
這是我的輸出,
在屏幕底部的小矩形是我創建的矩形。但是,當我點擊它時沒有任何反應。我查了一下座標,這裏是日誌,
x-0.925: y-0.5625
rect300.0: rect10.0
x-0.925: y-0.5625
rect300.0: rect10.0
x-0.925: y-0.5625
我嘗試使用以下方法檢查觸摸,
if (inputs.x > sprite.getX() && inputs.x < sprite.getX() + sprite.getWidth())
{
if (inputs.y > sprite.getY() && inputs.y < sprite.getY() + sprite.getHeight())
{
Gdx.app.log("sprite touched", "");
}
}
這也不起作用。任何想法,我犯了錯誤?請幫忙 。在此先感謝