Skip to content

1 #107

Description

@310019032
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;

public class MyGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture ballTexture;
    Vector2 ballPosition;
    Vector2 ballVelocity;

    @Override
    public void create() {
        batch = new SpriteBatch();
        ballTexture = new Texture("ball.png");
        ballPosition = new Vector2(100, 100);
        ballVelocity = new Vector2(3, 3);
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        
        updateBallPosition();
        
        batch.begin();
        batch.draw(ballTexture, ballPosition.x, ballPosition.y);
        batch.end();
    }
    
    private void updateBallPosition() {
        ballPosition.x += ballVelocity.x;
        ballPosition.y += ballVelocity.y;
        
        if (ballPosition.x < 0 || ballPosition.x > Gdx.graphics.getWidth() - ballTexture.getWidth()) {
            ballVelocity.x *= -1;
        }
        
        if (ballPosition.y < 0 || ballPosition.y > Gdx.graphics.getHeight() - ballTexture.getHeight()) {
            ballVelocity.y *= -1;
        }
    }
    
    @Override
    public void dispose() {
        batch.dispose();
        ballTexture.dispose();
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions