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 ;
        posball += directionObj;

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


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

public void render () {
    if (posYBall > 0) {
        posYBall -= fallSpeed;
    spriteBatch.draw(ball[1], posXBall, posYBall);
    ballDirection = 2;
    if (Intersector.overlaps(circleBall, screen)) {
        posXBall = ballDirection;
    } else {
        posXBall += ballDirection;
  • \$\begingroup\$ 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? \$\endgroup\$ – Peethor Feb 9 '19 at 17:07
  • \$\begingroup\$ 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? \$\endgroup\$ – Junior Albin Feb 9 '19 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.

  • \$\begingroup\$ 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. \$\endgroup\$ – Peethor Feb 10 '19 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.