I'm making a soccer game where you touch the screen and the player shoot the ball to the touched position with the objective of scoring goals when it hits the goal. The player is just a Sprite and the Ball and the Goal are Rectangles. What I'm trying to do here is when the Ball collides with the Goal the player changes its position to a random one on the screen and the ball resets to the player position, although I'm not actually getting the collision between the Rectangles. Any help would be appreciated.
TLDR : make so that when the ball collides with the goal, the players position changes and the ball resets to the player position.
Game class
private SpriteBatch batch;
private OrthographicCamera cam;
private Texture player1;
private Sprite player;
private Sprite bg;
private Texture back;
private Texture ball1;
private Rectangle ball = new Rectangle();
private Sprite bs;
private Texture goal1;
private Rectangle goal = new Rectangle();
private Texture line;
Ball b = new Ball();
public void create () {
cam = new OrthographicCamera();
cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch = new SpriteBatch();
batch.setProjectionMatrix(cam.combined);
player = new Sprite(player1);
player.setX(MathUtils.random(Gdx.graphics.getWidth()));
player.setY(MathUtils.random(Gdx.graphics.getHeight() / 2));
b.position.set(player.getX(), player.getY());
goal.setWidth(420);
goal.setHeight(130);
goal.setX(Gdx.graphics.getWidth()/4-20);
goal.setY(Gdx.graphics.getHeight() - 180);
ball.setX(b.position.x);
ball.setY(b.position.y);
ball.setWidth(40);
ball.setHeight(40);
}
public void render () {
Gdx.gl.glClearColor(255, 255, 255, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
b.update(Gdx.graphics.getDeltaTime());
batch.begin();
batch.draw(bg, 0, 0);
if (!Gdx.input.isTouched()) {
batch.draw(bs, b.position.x, b.position.y);
}else if (Gdx.input.isTouched()) b.shootToward(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY());
batch.draw(goal1, Gdx.graphics.getWidth()/4-20, Gdx.graphics.getHeight() - 180, 420, 130);
player.draw(batch);
if (goal.contains(ball)) {
player.setX(MathUtils.random(Gdx.graphics.getWidth()));
player.setY(MathUtils.random(Gdx.graphics.getHeight() / 2));
}
batch.end();
}
Ball class
public void shootToward(float targetX, float targetY) {
velocity.set(targetX - position.x, targetY - position.y);
}
public void update(float deltaTime) {
position.add(velocity.x * deltaTime, velocity.y * deltaTime);
velocity.scl(1 - (.98f * deltaTime));
}