what's wrong with my lookAt and move forward code?
- by alaslipknot
so am still in the process of getting familiar with libGdx and one of the fun things i love to do is to make basics method for reusability on future projects, and for now am stacked on getting a Sprite rotate toward target (vector2) and then move forward based on that rotation
the code am using is this :
// set angle
public void lookAt(Vector2 target) {
float angle = (float) Math.atan2(target.y - this.position.y, target.x
- this.position.x);
angle = (float) (angle * (180 / Math.PI));
setAngle(angle);
}
// move forward
public void moveForward() {
this.position.x += Math.cos(getAngle())*this.speed;
this.position.y += Math.sin(getAngle())*this.speed;
}
and this is my render method :
@Override
public void render(float delta) {
// TODO Auto-generated method stub
Gdx.gl.glClearColor(0, 0, 0.0f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// groupUpdate();
Vector3 mousePos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(mousePos);
ball.lookAt(new Vector2(mousePos.x, mousePos.y));
//
if (Gdx.input.isTouched()) {
ball.moveForward();
}
batch.begin();
batch.draw(ball.getSprite(), ball.getPos().x, ball.getPos().y, ball
.getSprite().getOriginX(), ball.getSprite().getOriginY(), ball
.getSprite().getWidth(), ball.getSprite().getHeight(), .5f,
.5f, ball.getAngle());
batch.end();
}
the goal is to make the ball always look at the mouse cursor, and then move forward when i click, am also using this camera :
// create the camera and the SpriteBatch
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
aaaand the result was so creepy lol
Thank you