-1
\$\begingroup\$

I've created a game which spawns a random colored ball in the top or bottom of the screen and moves to random direction with this method.

private Vector2 position;
private Vector2 velocity;

private void move(float toX, float toY) {
    velocity.set(toX - position.x, toY - position.y);
    velocity.nor();

    velocity.x *= SPEED;
    velocity.y *= SPEED;
}

Now, I want to add 2 rectangles in the middle of the game and when the ball meets the rectangles or the wall (outside of the screen) it should calculate the new move position, but I don't know the math for it.

Here's a picture which explains better what I want to have.

Ball.java

public void update(float dt) {

    if(!isActivated) {
        if(position.y >= MainGame.HEIGHT) {
            move(position.x, position.y - anim.getFrame().getRegionHeight());
        }
        if(position.y == MainGame.HEIGHT - anim.getFrame().getRegionHeight()) {
            move(10, 10);
            isActivated = true;
        }
    } else {
        activeTimer += dt;

        if(position.y < 0) {
            // I need the calculation here
        }
    }
}
\$\endgroup\$
0
\$\begingroup\$

We have two cases, the first case being your ball is not colliding. Because of Newtons First Law your ball will have the originally random assigned velocity, \vec{v_{i}}. The second case is the one we are interested which is collision.

Assuming we are operating in 2 dimensions then we can treat walls and edges of boxes as line segments. Using our current model which only accounts for velocity, we can reflect the balls current vector \vec{v} over vector \vec{N_{l}} which is normal to the line segment the ball collides with. This results in the new velocity vector of the ball, \vec{v_{r}}.

This is easier to understand using an image such as the one below.

angle_of_reflection

A more in-depth discussion can be found at Wolfram.com.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.