Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Question Simulating bounciness with Vector3.Reflect

Discussion in 'Physics' started by Mornedil, Nov 27, 2022.

  1. Mornedil

    Mornedil

    Joined:
    Feb 7, 2016
    Posts:
    19
    I have a ball, a kinematic RigidBody that I'm moving manually.
    I'm using Vector3.Reflect to change it's direction when it collides with other objects.
    That part is working fine, I'm using a spherecast to detect collisions, then moving the ball into contact with the other object, and then using Vector3.Reflect to get the new direction, which bounces the ball perfectly:

    Code (CSharp):
    1. _newVelocity = Vector3.Reflect(Velocity, _normal);
    However, I want to be able to control how "perfect" the new direction is - similar to how Bounciness works when letting the physics engine automatically control a Rigidbody. Where a bounciness of 1 means it perfectly retains momentum, and a value of 0 means it "sticks" to the wall but retains sideways momentum if it for example hit the wall at an angle:

    Vector3ReflectBounciness.png

    Any ideas how this can be achieved?

    I tried simply adding a multiplier to the _normal used in Vector3.Reflect, but it didn't work out well.
    I had a 2nd idea, of "scaling" the new velocity down along the normal vector, but I have no idea how that would be written as code
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,996
    could test what happens with Vector3.Lerp()
    so could lerp between Result and that 0 angle direction
     
    Mornedil and Edy like this.
  3. Mornedil

    Mornedil

    Joined:
    Feb 7, 2016
    Posts:
    19
    That's a good plan, but I'm not sure how to calculate that "0 bounciness" vector in the illustration.

    The values I have are the ones written in black in the illustration. The initial velocity, the normal of the surface hit, and the resulting velocity after a perfect bounce

    Edit: I figured it out after thoroughly reading through the Vector3 section on the wiki!
    Had to use Vector3.ProjectOnPlane to project the new velocity onto the collision normal.

    Code (CSharp):
    1. Vector3 _newVelocityA = Vector3.Reflect(Velocity, _normal);
    2. Vector3 _newVelocityB = Vector3.ProjectOnPlane(_newVelocityA, _normal);
    Where _newVelocityA is a perfect collision angle (bounciness 1), and _newVelocityB slides perfectly along the wall (bounciness 0).
    Should be able to just Vector3.Lerp between these now!
     
    Last edited: Nov 28, 2022
    mgear likes this.