- Home /
Moving a ball in the opposite direction of where it hits
Hi guys,
I am making a small arkanoid style game for practice. I currently have the ball bouncing around the screen with the following:
if (viewPos.x < 0 || viewPos.x > Screen.width)
{
Vector2 vel = ballRB.velocity;
vel.x = -vel.x;
ballRB.velocity = vel;
}
if (viewPos.y < 0 || viewPos.y > Screen.height)
{
Vector2 vel = ballRB.velocity;
vel.y = -vel.y;
ballRB.velocity = vel;
}
I am now at the part where I need to bounce the ball off the bricks. I determine what side of the brick was hit (currently using the bottom of the brick) and want to bounce the ball in the opposite direction.
If I'm not mistaken, should this code not be the same as the y position above? As i just want to bounce it back in the opposite direction, which is already what happens when the ball hits the top of the screen, instead, when I run the code below and the ball hits the underside of a brick, the ball just stops dead in it's tracks
private void OnColliderEnter2D(Collider2D col)
{
if(col.gameObject.CompareTag("Brick"))
{
//bottom of the brick
if (transform.position.y <= col.transform.position.y - (col.bounds.size.y / 2))
{
Vector2 vel = ballRB.velocity;
vel.y = -vel.y;
ballRB.velocity = vel;
Destroy(col.gameObject);
}
}
}
I know I could bounce the ball using a physics material but I would like to try do it without one.
Thanks in advance
Answer by JayFitz91 · Apr 16, 2018 at 01:32 PM
Just in case anyone was wondering, I managed to solve this by using the relative velocity of the colliding object, which bounces it back in the opposite direction the ball was going.
ballRB.velocity = new Vector2(-col.relativeVelocity.x, col.relativeVelocity.y);