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. Dismiss Notice

Change direction based on normal

Discussion in 'Scripting' started by CasualDutchman, Feb 3, 2021.

  1. CasualDutchman

    CasualDutchman

    Joined:
    Jan 20, 2016
    Posts:
    37
    I have tried multiple different things, but I just can't seem to find the solution I want.

    I have this directional vector crawling up a wall.
    After some length, it changes it's direction based on a random angle.

    It works fine with this equation:
    Code (CSharp):
    1. var randomDir = (Quaternion.FromToRotation(Vector3.forward, -current.Normal) * Quaternion.AngleAxis(rng.Range(arcX, arcY), Vector3.forward)) * current.Direction;
    The gif shows what the code does
    White: The normal of the collider.
    Red: The previous direction
    Magenta: The new direction based on a random angle (-30, 30)

    The problem, it only works when the normal is like Vector3.back.
    Can someone help me with this? How can I make it work when the normal is Vector3.up for example?

    help.gif
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    I'm not sure I 100% grasp your question, but you can produce an arbitrary rotation around an arbitrary axis with this:

    https://docs.unity3d.com/ScriptReference/Quaternion.AngleAxis.html

    From that, you can change any other orientation by multiplying it by the above-created Quaternion.

    I know that's super-general, but if you have a normal, that could perhaps be the axis you want to rotate some random amount around, and you would use that, then modify your other orientation by it.
     
  3. CasualDutchman

    CasualDutchman

    Joined:
    Jan 20, 2016
    Posts:
    37
    I was overthinking the solution.
    As you can see from the line of code I was using, it uses a lot of different functions.
    While this line of code does the trick
    Code (CSharp):
    1. var randomDir = Quaternion.AngleAxis(rng.Range(arcX, arcY), -current.Normal) * current.Direction;