Search code examples
unity-game-enginegravitycylindrical

Unity: Faux Gravity - inner Capsule/ Cylinder


I'm struggling with false Gravity in a Cylinder or Capsule. Basically I thought I could take the same Code as for spherical gravity, which does not work. So I changed some lines to get a better result.

    [SerializeField] float gravity = 10;

public void Attract ( Transform target )
{
    Vector3 gravityUp = (target.position - new Vector3(transform.position.x, transform.position.y,target.position.z)).normalized;
    Vector3 bodyDown = -target.up;

    Rigidbody rb = target.GetComponent<Rigidbody>();
    rb.AddForce(gravityUp * gravity);

    Quaternion targetRotation = Quaternion.FromToRotation(bodyDown, gravityUp) * target.rotation;
    targetRotation.x = 0;

    target.rotation = Quaternion.Slerp(target.rotation, targetRotation, 30.0f * Time.deltaTime);

}

This worked OK on the first try. But the Player(target) can't rotate one the Y-Axis. Does anyone have any ideas?


Solution

  • OK, I tried the following.

     Quaternion targetRotation = Quaternion.FromToRotation(bodyDown, gravityUp) * target.rotation;
    targetRotation.x = 0;
    
    target.rotation = Quaternion.Slerp(target.rotation, targetRotation, 30.0f * Time.deltaTime);
    

    Now I use the Surface normal to rotate the Player.

    if (Physics.Raycast(attractedBody.transform.position + attractedBody.transform.forward, -attractedBody.transform.up, out hit, distance))
        {
            surfaceNorm = hit.normal;
        }
    

    But without Rigidbody Contrains the Player starts rotating without any Input. So I have to use:

    rb.constraints = RigidbodyConstraints.FreezeRotation;
    

    This works.