我有一个碰撞矩形(libgdx,而不是awt)设置为球的坐标。我想做的是检查我是否点击它。两个问题:
a。)我不知道矩形坐标的原点在哪里
b。)我无法找到正确的方法来纠正水龙头的位置
我该怎么办?
按请求编辑:
public void create() {
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
...
camera.unproject(tmpPos);
}
public void render() {
if (Gdx.input.isTouched()) {
float x = Gdx.input.getX();
float y = Gdx.input.getY();
tmpPos.set(x, y, 0);
camera.unproject(tmpPos);
// now the world coordinates are tmpPos.x and tmpPos.y
if (target.contains(tmpPos.x, tmpPos.y)) {
System.out.println("Touched. ");
score++;
}
System.out.println("Score: " + score + "..." + "X: " + (int) tmpPos.x + "...Y: " + (int) tmpPos.y);
...
}
答案 0 :(得分:0)
我假设你有一台正交相机。 (如果没有它,你真的无法制作游戏)
您不需要知道其来源以检查是否被触摸,但如果您愿意,原点是
float originX = rectangle.x + rectangle.width / 2f;
float originY = rectangle.y + rectangle.height / 2f;
无论如何,您需要取消投影触摸坐标,这意味着您需要从屏幕位置转换到摄像机位置(世界位置)。 为此你需要一个Vector3,更喜欢在你正在使用的方法之外的某个地方声明它,因为不推荐在每个帧中初始化一个对象。
Vector3 tmpPos=new Vector3();
现在检查你的矩形是否被触摸,你想要的任何地方。 你有2种方法可以做到这一点。
public void render(float delta){
if (Gdx.input.isTouched() { // use .isJustTouched to check if the screen is touched down in this frame
// so you will only check if the rectangle is touched just when you touch your screen.
float x = Gdx.input.getX();
float y = Gdx.input.getY();
tmpPos.set(x, y, 0);
camera.unproject(tmpPos);
// now the world coordinates are tmpPos.x and tmpPos.y
if (rectangle.contains(tmpPos.x, tmpPos.y)) {
// your rectangle is touched
System.out.println("YAAAY I'm TOUCHED");
}
}
}
选项2,使用输入监听器,因此您只需检查何时触发触摸事件。 在屏幕/游戏的show / create方法中添加输入监听器
public void show() {
// .....
Gdx.input.setInputProcessor(new InputProcessor() {
// and in the method that you want check if the rectangle is touched
@override
public void touchDown(int screenX, int screenY, int pointer, int button) {
tmpPos.set(screenX, screenY, 0);
camera.unproject(tmpPos);
// now the world coordinates are tmpPos.x and tmpPos.y
if (rectangle.contains(tmpPos.x, tmpPos.y)) {
// your rectangle is touched
System.out.println("YAAAY I'm TOUCHED");
}
}
// and the rest of the methods
// ....
//
});
}
我会用第二种方式。 让我知道它是否适合你。
答案 1 :(得分:0)
我的最终解决方案是:
将矢量设置为触摸坐标,但是,使用此更正:(Gdx.input.getY() * -1) + cy
其中cy
是屏幕的高度。然后,我取消投影该矢量,并绘制它。而不是没有校正的反y位置,圆圈直接跟在我的手指下面并完美地与世界上的其他物体通信。