1
\$\begingroup\$
            if (bucket.x > 0) {
                rect.x += 200 * Gdx.graphics.getDeltaTime();
            }
            if (rect.x < 0) {
                rect.x = 0;
                rect.x += 200 * Gdx.graphics.getDeltaTime();
            }

            if (rect.x > Gdx.app.getGraphics().getWidth() - 30) {
                rect.x -= 200 * Gdx.graphics.getDeltaTime();
            }

I have a rectangle, it has a width of 30 px, I want to move from it's x point till the edge of the screen, when it gets there I want it to go back to the other edge. it's only moving till it hits one edge and it stops.

This might be a basic question but I'm new to Libgdx and I can't find documentation. If I add a while (true ) loop the app would stop working. Basically I want it to move infinitely along the x axis back and forth from right edge to the left edge.

I tried something like

`if (rect.x > 800 - 30) `

it won't work either and I don't like specifying the width of the device explicitly. Basically it's moving but never detecting the right edge of the screen

\$\endgroup\$
1
\$\begingroup\$

You need to move by a determined speed your rectangle once a loop.

// In your declaration
float speed = 15; // Pixels / second

// In your game loop
rect.x += speed * Gdx.graphics.getDeltaTime();

When you reach the edge of the screen, you need your speed to become the opposite of your current speed

// Check if rectangle is out of screen
if (rect.x + rect.width > screenWidth || rect.x < 0)
{
    speed = -speed;
}

That's it, and it works exactly the same for Y

\$\endgroup\$
1
  • \$\begingroup\$ You shouldn't define your speed as pixels / second sine this will make your game play different in different window sizes unless you use a viewport. But if you use a viewport I argue that you should have your viewport in an abstract unit instead of pixels (for example meters). \$\endgroup\$ – Charanor Jan 16 '17 at 11:20
1
\$\begingroup\$

In order to simulate physical event (bounce, collision..) you can use Box2d module from LibGDX. instead of calculating the transformation you define the object, apply a force and see it applies to your objects.

\$\endgroup\$

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.