# How to implement "move to touch location" function?

What is the formula/logic to implement moving an object towards a TOUCHED location. I want character A to move to my finger and it must be accurate. Here is what I have tried so far:

    @Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// coordinates come in pixels so convert to world units
scaleX = screenX / (Gdx.graphics.getWidth() / 10f);
scaleY = screenY / (Gdx.graphics.getHeight() / 7f) * -1;

float angle = new Vector2(scaleX - mishi.getPosition().x, scaleY
- mishi.getPosition().y).angle();
....
....
mishi.getVelocity().x = (float) (Math.cos(angle) * 13);
mishi.getVelocity().y = (float) (Math.sin(angle) * 13);


This gets my character moving but basically no where in the direction I click. If I click in the same point twice, it will move him in 2 different directions

• "can't get it right" and "didn't like it" and "partially working" are all poorly defined. Use technical descriptions. Exactly what is it doing and exactly what do you want it to do? Commented May 2, 2014 at 20:51

This simply sets the acceleration to a factor proportional to the distance between the points.

If you want the character to move at a constant velocity, you should instead get the angle between points and cast them to a static vector.

To make the character stop, set its velocity and acceleration to 0.

• I don't understand, lets not talk about constant speed or stopping, simply moving to where I touch, can you give me a formula for that? if mine is wrong how can I fix it, I just want to touch and have my character move to that location. You mentioned angle but what do I do with the angle, I have it right now just doing .angle() on the distance Commented May 2, 2014 at 20:44
• The code should already do that, assuming toX and toY are set corectly, and the co-ordinate plane is inverted on the x-axis. Also assuming that the interface for setAcceleration() as as expected. How does it behave? Commented May 2, 2014 at 20:46

I can't guarantee that this is your problem, but are you taking into consideration that the coordinate system for input starts at the top left, with x growing to the right as usual, but y growing downwards?

In other words, the x-value is the same in world coordinates as in the screen coordinates, but the y differs. To get the y-value from screen to world coordinates, simply use

yWorld = Gdx.graphics.getHeight() - Gdx.input.getY();


Or do it as outlined in this answer: https://stackoverflow.com/questions/16514152/libgdx-coordinate-system-differences-between-rendering-and-touch-input