# LibGDX: Change Direction

I want to move an object on screen and when the object intersect with the obstacle he change the position, for example he's going to the right and he found an obstacle, so he change to the left.

    directionObj = 2;
if(Intersector.overlaps(obj, screen)){
posBall -= directionObj ;
}else{
posball += directionObj;
}


but when the object found the obstacle he dont change the direction

[edited]

this is my render. When the ball intersect with the screen, he dont change the direction

public void render () {
fallSpeed++;
if (posYBall > 0) {
posYBall -= fallSpeed;
}
spriteBatch.begin();
spriteBatch.draw(ball[1], posXBall, posYBall);
spriteBatch.end();
ballDirection = 2;
if (Intersector.overlaps(circleBall, screen)) {
posXBall = ballDirection;
} else {
posXBall += ballDirection;
}

• Because I can't see your variable declarations, I can't be sure. It seems like you're checking if the ball (or whatever your obj is) is on screen. Then it moves jn one direction. Otherwise, the other direction. But how can a position be a floating point number? – Peethor Feb 9 at 17:07
• when the obj collide with the obstacle he decrement the position value, but when he take the next position, he increment again. For example the position is 30 so he decrement and now the position is 20, then he increment again and the position is 30 again and keep in this loop. How can I solve this problem? – Junior Albin Feb 9 at 17:27

Make sure you declare ballDirection somewhere where it will retain its value throughout multiple cycles/frames. For instance, in the "create()" function. If you declare it as a positive value every frame, it will always try to go right first.

if(Intersector.overlaps(circleBall, screen))
{
ballDirection *= -1 ;
}
posXBall += ballDirection;


This will always add the speed to the balls current position, and only change the direction when a collision is detected.

• I've edited the answer to more closely resemble your edited question, but it doesn't answer what happens when your ball reaches the bottom of your screen. You will need to find a way to differentiate between reaching the bottom of the screen and reaching the side of the screen. If you have the screen size, this can easily be done by using the ball's position and size. If posXBall + circleBall.width >= screen.width, then it reached the side of the screen. – Peethor Feb 10 at 7:56
• Thanks for the help, this solved my problem – Junior Albin Feb 11 at 13:25