Saturday, May 2, 2015

java - How to detect the border of the screen and bounce back?


            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



Answer



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


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...