Best way to detect the touched object (moving) from collection in libgdx

好久不见. 提交于 2019-12-01 08:40:16
Sajal Dutta
public static boolean pointInRectangle (Rectangle r, float x, float y) {
    return r.x <= x && r.x + r.width >= x && r.y <= y && r.y + r.height >= y;
}

In your update-

if(pointInRectangle(flyRectangle, Gdx.input.getX(), Gdx.input.getY())){
  // Do whatever you want to do with the rectangle. maybe register them for effect
}

You can also look into Intersector class.

Now for collision, if your game is fast-paced, with lots of enemies moving around that the player can collide with, sooner or later you will use a box2d type library because if the movement speed is high, you might not get any collision callback. Things might go through each other. You can try predicting the collision before it happens using the velocity and deltaTime, but it's still not going to be enough and you will end up reinventing the wheel.

Mario's SuperJumper is a great demo to start libGDX. Try it.

EDIT:

Have an instance member-

Vector3 touchPoint;

On create-

touchPoint = new Vector3();

On update-

camera.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));

if (Gdx.input.justTouched()) {
    if (pointInRectangle(rectangle, touchPoint.x, touchPoint.y)) {
    }
}

Please take note of the coordinate system in libGDX. For testing, create one rectangle on screen. On click, print/debug the coordinates of both the rectangle and touchPoint.

I've solved the problem by making an invisible rectangle which will follow the tap location and I made an if statement checking for overlapping of the invisible rectangle and checking for if the screen was just tapped.

Here is the code:

if(Gdx.input.isTouched()) {
        Vector3 pointerPos = new Vector3();
        pointerPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        cam.unproject(pointerPos);
        touchPos.x = pointerPos.x /*+ 64 / 2*/;
        touchPos.y = pointerPos.y /*+ 64 / 2*/;
    }

    Iterator<Rectangle> iter = raindrops.iterator();
    while(iter.hasNext()) {
        Rectangle raindrop = iter.next();
        raindrop.y -= 300 * Gdx.graphics.getDeltaTime();
        if(raindrop.y + 64 < 0) {
            iter.remove();
        }
        if(raindrop.overlaps(touchPos) && Gdx.input.justTouched()) {
            iter.remove();
            dropSound.play();
        }

all of this code is in the render method.

P.S: Change raindrops to the fly objects you want

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!