0
\$\begingroup\$

I have a sprite that moves from the bottom left of the screen to the top right. What I want to know is how would i make it turn around and go in the opposite direction, and continue this loop.

I tried negating the direction of the vector but that doesnt work.

This what i have right now:

public void create() {
    // Game Initialization  
    v = new Vector2(Gdx.graphics.getWidth() - 0, Gdx.graphics.getHeight() - 0); 
    v.nor();
    v.scl(100);

    spriteBatch = new SpriteBatch(); 
    bug = new Sprite(new Texture("EnemyBug.png"));
    bug.setSize(50, 85);
    bug.setOrigin(0,0);//Gdx.graphics.getHeight() / 5, Gdx.graphics.getHeight() / 5);
    bug.setPosition(1,1);//Gdx.graphics.getWidth() - 50, Gdx.graphics.getHeight() - 50);
    bug.rotate(v.angle());

    rotDeg = 5;
}

@Override
public void render() {
    // Game Loop

    Gdx.gl.glClearColor(0.7f, 0.7f, 0.2f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    spriteBatch.begin();        

    if(bug.getX() >= (int)(Gdx.graphics.getWidth() - 100) && bug.getY() >= (int)(Gdx.graphics.getHeight() - 100)){
        turn = !turn;
    }
    else if(bug.getX() <= 50 && bug.getY() <= 50){
        turn = !turn;
    }


    if(!turn){          
        bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    }
    else{
        bug.translate(-(v.x * Gdx.graphics.getDeltaTime()), -(v.y * Gdx.graphics.getDeltaTime()));
    }

    bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    bug.draw(spriteBatch);
    spriteBatch.end();
}
\$\endgroup\$
1
  • \$\begingroup\$ Negating the direction vector should make your sprite move to the opposite direction. Can you show us the code where you did that and it didn't work? What else did you do to just negating the vector? Did you have some condition when it should negate? \$\endgroup\$
    – Lasse
    Commented Oct 31, 2014 at 22:51

1 Answer 1

1
\$\begingroup\$

You have a translate function outside of the if statement.

    .
    .
    .
    if(!turn){          
        bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    }
    else{
        bug.translate(-(v.x * Gdx.graphics.getDeltaTime()), -(v.y * Gdx.graphics.getDeltaTime()));
    }

    bug.draw(spriteBatch);
    spriteBatch.end();
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .