S
S
Sergey Semenko2015-02-20 15:26:12
Java
Sergey Semenko, 2015-02-20 15:26:12

How to correctly implement movement and direction change?

It is necessary that the object by default move up and to the right, and when it reaches the edge of the screen, it changes its direction. This can be found on screensavers or somewhere else)
I got this, but maybe you need it wrong?

public class MyGdxGame implements ApplicationListener {
  SpriteBatch batch;
  TextureRegion npc;
  
  Vector2 velocity;
  
  float x = 0;
  float y = 0;
  
  float width;
  float height;
  
  boolean left = false;
  boolean right = false;
  boolean down = false;
  boolean up = false;

  @Override
  public void create() {
    batch = new SpriteBatch();
    velocity = new Vector2();
    
    Texture texture = new Texture(Gdx.files.internal("npc.png"));
    npc = new TextureRegion(texture);
    width = npc.getRegionWidth() / 2;
    height = npc.getRegionHeight() / 2;
  }

  @Override
  public void render() {        
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    
    velocity.x = 100 * Gdx.graphics.getDeltaTime();
    velocity.y = 100 * Gdx.graphics.getDeltaTime();
    
    right = !left || x - width < 0;
    left = !right || x + width > Gdx.graphics.getWidth();
    up = !down || y - height < 0;
    down = !up || y + height > Gdx.graphics.getHeight();
    
    if (left) velocity.x = -velocity.x;
    if (down) velocity.y = -velocity.y;
    
    x += velocity.x;
    y += velocity.y;
    
    batch.begin();
    batch.draw(npc, x, y, width, height);
    batch.end();
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question