Relative gravity simulation in unity.

in #programming5 months ago

I just want to share a method I figured out for handling gameobject/ridgidbody orientation when dealing with relative gravity. I added comments to the code to help explain certain functions.

using UnityEngine;

public class GroundModifications : MonoBehaviour
{
    // Asssign the sprite object in the inspector
    public Transform spriteTransform;
   //This stores the original sprite rotation at the start of the simulation
    public Quaternion SpriteReal;
    void Start()
    {
       //save the sprite rotation
        SpriteReal = spriteTransform.rotation;
    }

    // Update is called once per frame
    void Update()
    {
      //code kept in separate function for organization purposes
        OrientToGround();
    }

    void OrientToGround()
    {
      //ground layer mask
        int layerMask = 1 << 8;
      //store hit value
        RaycastHit hit;
        if (!Physics.Raycast(transform.position, -transform.up, out hit, 10.0f,
            layerMask))
        {
           //If no surface is found reset gameobject rotation
            transform.rotation = SpriteReal;
        }
       //get the angle between the downward direction of the game object and the inward facing normal
        var AngleToGround = Vector3.SignedAngle(-transform.up, -hit.normal,transform.forward);
       //Get the distance between the game object and the point the ray trace hit
        var Distance = Vector3.Distance(hit.point, transform.position);
        //Prevent Player From Being Stuck (if they get caught at an angle where they cant upright themselves)
        if ( Distance >= 1.0f)
        {
            transform.Rotate(transform.forward,5.0f);
        }
       //if the angle is less then or greater then zero rotate gameobject toward it
        if (!AngleToGround.Equals(0.0f))
        {
            transform.Rotate(transform.forward, AngleToGround);
        }
        //reset Sprite Rotation (this code is to reset a sprite im messing with so i can manually handle how i want to rotate it for stylistic purposes)
        spriteTransform.rotation = SpriteReal;
    }
}