-3

I am trying to implement balls that change their direction when they hit an obstacle(in this case a fixed ball). I can detect when a collision occurs but I don't know how to modify the direction of a ball once it hits an obstacle. Here's some code:

struct Vec2
{
    float x, y;
};

struct Ball
{
     void onCollision(const Ball& fixedBall)
     {
         // This function will be called when a collision occurs
         // Speed will be constant, only direction needs to change
     }

     void update()
     {
         position += direction * speed; 
     }

     Vec2 position, direction; // direction is a normalized vector
     float speed, radius; 
};

1 Answers1

1

You will need to invert the speed by negating it.

if (collision)
  speed = speed * -1
Rob Brander
  • 3,702
  • 1
  • 20
  • 33