简体   繁体   中英

Move sprite to mouse click [Libgdx];

I'm new to libgdx Game programming and I want to create an RPG kind of game.

I want to make the player move towards the mouse/touch position.

I have calculated a logical way to do this, but it seems that the player moves only one frame at a time, which means that the player need to click several times to get to the right position, instead of walking to the click position frame by frame only by one click.

My code:

Gdx.input.setInputProcessor(new Input(){
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        projected = new Vector3(screenX, screenY, 0);
        cam.unproject(projected);

        if(projected.x != position.x || projected.y != position.y){
            float pathX = projected.x - position.x;
            float pathY = projected.y - position.y;

            float distance = (float) Math.sqrt(pathX * pathX + pathY * pathY);
            float directionX = pathX / distance;
            float directionY = pathY / distance;

            position.x += directionX * Speed;
            position.y += directionY * Speed;
        }

        return true;
    }

Your method is called (once) every time you touch the screen. Your method changes the position (once) with

position.x += directionX * Speed;
position.y += directionY * Speed;

So every touch of the screen only moves your Sprite once.

Your Screen class has a method render(float deltaTime) . This gets called repeatedly, with the argument giving the time since it was last called. This makes it a useful method in which to do things you need to happen repeatedly (like update a sprite's position).

So what you really want to do inside your touchDown() is to set your Sprite's direction (as a field contained in your Sprite object). You can then write a method something like

update(float deltaTime) {
   position.x += directionX * Speed * deltaTime;
   position.y += directionY * Speed * deltaTime;
}

inside your Sprite's class. This is almost what you wrote, but the * deltaTime ensures the amount the position changes by is only the distance that would have been covered since the previous call of this method.

This method still never gets called though, so you need to call it from your Screen.render(deltaTime) method:

render(float deltaTime) {
   mySprite.update(deltaTime);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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