public void update(float delta){
position.x = getX();
if(Gdx.input.justTouched()){
for(;position.x < 864; position.x = position.x + 0.5f){
setX(getX() + 3f*delta);
}
}
}
The above code shows the loop that makes a block move which is like the character from one side of the screen to the other and stop when it reaches the x coordinate of 864. The loop runs fine when it's on it's own but it runs as soon as I compile the game. What I want it to do is to run the loop when the mouse is clicked anywhere on the screen. But what actually happens is that it runs the loop only once and I have to click the mouse multiple times before the loop is complete and the block is on the other side of the screen (images below). Can someone please shed some light on how I would go about setting it up so that it runs the whole loop and moves the block from left to right with a single mouse click.
Thanks a lot.
Images: This is where the block starts at: https://i.sstatic.net/n5CDU.png This is what I want it to end up like when the mouse is clicked: https://i.sstatic.net/lnZA1.png
You can't use loops like this in update
because they will block the render loop. The render loop already provides the loop, so you just need to increment it on each call to update. Keep a boolean to decide whether your movement needs to start. Something like this:
boolean hasBeenTapped = false;
public void update(float delta){
if (Gdx.input.justTouched())
hasBeenTapped = true;
if (hasBeenTapped && getX() < 864)
setX(getX() + 3f*delta);
}
If you want to use scene2d, then it has its own actions system that handles this stuff for you, possibly more intuitively than this. I personally use scene2d only for UI stuff though, because I find it too time consuming/restrictive to set up the game code with.