简体   繁体   English

按下矩形时打印文本 libgdx

[英]Print text when a rectangle is pressed libgdx

i have created a rectangle我创建了一个矩形

public Rectangle rectangle_hitbox;

It has the coordinates and dimensions of the enemies.它有敌人的坐标和尺寸。 In the render method, I want that when this rectangle is pressed, the string "Done" is printed.在渲染方法中,我希望当按下这个矩形时,打印字符串“Done”。 I tried with:我试过:

if(Gdx.input.isTouched()){
   System.out.println("Done");
} else {
   System.out.println("Missed");
}

But it works anywhere on the map and not only in rectangles但它适用于地图上的任何地方,而不仅仅是矩形

The Gdx.input.isTouched() method doesn't know about the position of your rectagle. Gdx.input.isTouched()方法不知道矩形的位置。 It just check whether the screen is touched or not.它只是检查屏幕是否被触摸。

Try using Gdx.input.getX() and Gdx.input.getY() to get the coordinates of the click or touch event when the screen is touched and check these coordinates against the coordinates of your rectangle.尝试使用Gdx.input.getX()Gdx.input.getY()在屏幕被触摸时获取单击或触摸事件的坐标,并根据矩形坐标检查这些坐标。

Also don't forget to unproject the coordinates if you are using a camera .如果您使用camera ,也不要忘记取消投影坐标。 See this answer for more information.有关更多信息,请参阅此答案

if(Gdx.input.isTouched()){
    Vector3 touchPosition = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0f);
    // TODO maybe unproject the position using camera.unproject(touchPosition);
    if (isTouchInsideRectangle(touchPosition)) {
        System.out.println("Done");
    }
    else {
        System.out.println("Missed");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM