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

后端 未结 2 425
天命终不由人
天命终不由人 2021-01-14 12:33

This is my first attempt in game development. I just started experimenting libgdx and understanding the different aspects of game programming. I looked at the sample project

相关标签:
2条回答
  • 2021-01-14 13:15
    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.

    0 讨论(0)
  • 2021-01-14 13:17

    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

    0 讨论(0)
提交回复
热议问题