简体   繁体   中英

Control sprite rotation (it's spinning like crazy)

So, I have created a texture, and then a sprite. On my render() method, I am check for user input. If the user has touched/clicked, then I want my sprite to rotate 90 degrees ONCE.

Right now the rotation works. However, it rotates multiple times per click!

How can I make it rotate only once per touch? I have a feeling that I might have to use delta time, and that occurs because the render method is being called frequently, but I don't know how to fix it... Thanks!

public class MyGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture img;
    Sprite sprite;

    @Override
    public void create () {
        batch = new SpriteBatch();
        img = new Texture("badlogic.jpg");
        sprite = new Sprite(img);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        sprite.draw(batch);
        batch.end();

        if (Gdx.input.isTouched()) {
            rotateRight();
        }
    }

    private void rotateRight() {
        sprite.setRotation(sprite.getRotation() - 90);
    }
}

Right now you are polling input inside of your render method. Polling simply checks the status of the input (is it touched or not) and does not care for any actual "event" occurred.

Instead of this you need to look for input events via event handling as this will give you access to the actual event of the screen being touched or untouched. You can do this by implementing InputProcessor which will give you access to override a bunch of touch event methods so you can execute your rotate method only on the event of the touch.

Example:

public void update() 
{
     Gdx.input.setInputProcessor(new InputProcessor() {
        @Override
        public boolean TouchDown(int x, int y, int pointer, int button) {
            if (button == Input.Buttons.LEFT) {
                rotateRight();
                return true;
            }
            return false
        }
    });
}

Don't forget to call your update() method from your render method. I put it in a separate function just for readability and not to clog up your rendering code.

You can also have your class implement InputProcessor and override the methods in your class so you do not have to do it inline as I did above.

if (Gdx.input.justTouched() && Gdx.input.isTouched()) {
    rotateRight();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM