0
\$\begingroup\$

I'm working on a 2d side-scrolling RPG-ish game. Currently the movement of the main character(hero) is based on the A and D keys, because it's 2d and I don't really care about jumping. I would like to change it to a mouse oriented system. Something like this: if the hero is at position 100(x-axis) and I click at x=200, it would move(tween/ease) to 200px with 50px/s. PS: I'm using java with libgdx.

\$\endgroup\$
2
\$\begingroup\$

This is simply a combination of a few simple steps.

First, get the mouse position, Gdx.input.getX() will give you the mouse X position. You'll want to get that position at the time the mouse button was pressed.

Now, that you have a target, move your hero towards it. You can do that with something like:

float deltaV = deltaTime * speed;
if (Math.abs(target.X - hero.X) > 1) {
    if (hero.X < target.X) {
        hero.X += deltaV;
    }
    if (hero.X > target.X) {
        hero.X -= deltaV;
    }
}

You'll want to either add some speed up and slow down functionality in there to arrive exactly at the target, or do something like check to see if the last update put you past the target and if so, set the position to the target position. This code will get you close and if you end up within 1 unit of the target position it will stop.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.