球与固定球碰撞

Ball to fixed ball collision

本文关键字:碰撞      更新时间:2023-10-16

我正在尝试实现在遇到障碍物时改变方向的球(在本例中为固定球(。我可以检测到碰撞何时发生,但我不知道一旦球撞到障碍物,如何修改球的方向。下面是一些代码:

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; 
};

您需要通过否定速度来反转速度。

if (collision)
  speed = speed * -1