1
\$\begingroup\$

I'm trying to make an image move towards another point. I only have the current X/Y and the destination X/Y + Speed.

That's it.

public void Draw(SpriteBatch batch, int goalX, int goalY){
    destX = goalX - posX;
    destY = goalY - posY;

    dist = Math.sqrt(destX * destX + destY * destY);
    destX = destX / dist;
    destY = destY / dist;

    posX += destX * this.speed;
    posY += destY * this.speed;

    batch.draw(img, posX, posY);    
}

This is my code, it kinda moves towards the object, but it moves past the object to a certain distance and then starts spazzing out for some reason.

The other point is also moving, just so you know.

Anybody can help me with this?

\$\endgroup\$
1
\$\begingroup\$

You have to check if the distance travelled is greater than what remains to travel; if it is, you arrive at your destination on that frame, explicitly set the position instead of 'travelling':

public void Draw(SpriteBatch batch, int goalX, int goalY){
    destX = goalX - posX;
    destY = goalY - posY;

    dist = Math.sqrt(destX * destX + destY * destY);
    destX = destX / dist;
    destY = destY / dist;

    travelX = destX * this.speed;
    travelY = destY * this.speed;

    distTravel = Math.sqrt(travelX * travelX + travelY * travelY);

    if ( distTravel > dist )
    {
        posX = destX;
        posY = destY;
    }
    else
    {
        posX += travelX;
        posY += travelY;
    }

    batch.draw(img, posX, posY);    
}
\$\endgroup\$
1
\$\begingroup\$

LibGDX provides actions for Actors which make moves like this easy.

If your image is an Image class, it extends Widget which extends Actor so you can easly make him move (even with tons of interpolation types!):

I'll write you an example:

public SomeScreen implements Screen{

    Image someImage;

    //optional
    Stage stage;

    public SomeScreen(){
        someImage = new Image(//Load the image);
        someImage.setPosition(0,0); // left down corner of the screen

        float destinationX = Gdx.graphics.getWidth() - someImage.getWidth();
        float destinationY = Gdx.graphics.getHeight() - someImage.getHeight();

        // we move the actor to the destination point in 3 seconds
        someImage.addAction(Actions.moveTo(destinationx, destinationY, 3f)); 

        // remember that you should add the image to the stage here:
        stage.addActor(image);
    }


    public void draw(SpriteBatch batch, int goalX, int goalY){

        // if you don't have a stage, you should call:
        image.act(Gdx.graphics.getDeltaTime());
        batch.draw(image, image.getX(), image.getY(), image.getWidth(), image.getHeight());

        // if you have a stage (recommended)
        stage.act(delta);
        stage.draw();
    }
}
\$\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.