- Home /
Simulate a ball bouncing off of a linecast?
In my game, the player can form a "beam" via linecast (blue line in pic) from Character A (blue sphere in pic) and Character B (blue capsule in pic). Each character is controlled by a thumbstick and can move around the 2D level and the beam can be activated at any time. In this level, I'd like for the white ball to bounce off of the beam as if the beam were a wall. Below are two examples of what I'd like the ball's trajectory to look like.
So far, my code logic works like this: beam.cs does a linecast from Character A to Character B. The linecast detects the white ball's collider and calls a coroutine called BounceOffBeam() on ball.cs to change the white ball's velocity. But right now BounceOffBeam() does nothing because I can't wrap my head around how to calculate the white ball's new velocity after it "bounces" off of the beam's linecast.
public class Ball : MonoBehaviour
{
// called by beam when it hits this collider
public IEnumerator BounceOffBeam()
{
// store ball's velocity
Vector3 thisVel = rb.velocity;
// stop movement
rb.velocity = Vector3.zero;
// wait for physics update
yield return new WaitForFixedUpdate();
// SET NEW VELOCITY HERE.
}
}
Any help on how to get that new velocity would be much appreciated!