How to move textures using libGdx?

Asked

Viewed 260 times

0

I made this example of code that draws a texture on the user screen:

package com.example.myapp;

import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx..graphics.g2d.*;

public class MyGdxGame implements ApplicationListener
{
    TextureRegion image;
    @Override
    public void create(){
        Texture texture = new Texture(Gdx.files.internal("stick.png"));
        image = new TextureRegion(texture, 25, 0, 250, 250);

    }
    @Override
    public void render(){
        Gdx.gl.glClearColor(1,1,1,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(image, 0, 0, 100, 100);
        batch.end();

    }
    public void dispose(){
        batch.dispose();
    }
    public void resize(int width, int height){

    }
    public void pause(){

    }
    public void resume(){

    }

}

How do I move it to the coordinates I give it?

1 answer

0


Add an attribute of the type Vector2 to class Mygdxgame to represent the position of the texture
In the method create() create an instance containing your initial position:

private Vector2 texturePosition;
TextureRegion image;

@Override
public void create(){
    Texture texture = new Texture(Gdx.files.internal("stick.png"));
    image = new TextureRegion(texture, 25, 0, 250, 250);

    texturePosition = new Vector2(100,100);
}

In the method draw(), pass the values xand y of texturePosition to the method batch.draw:

batch.draw(image, texturePosition.x, texturePosition.y);

Declare a method to change texture position:

private void moveTextureTo(float x, float y){

    texturePosition.x = x;
    texturePosition.y = y;
}

When you want to move the texture call this method:

moveTextureTo(120, 120);
  • 1

    Thanks for the reply worked well ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.