Home > Net >  How to jump when player is upside down in a spherical world, using FauxGravity?
How to jump when player is upside down in a spherical world, using FauxGravity?

Time:02-21

What I try to do

Im trying to get jumping working all over the sphere and not just at the top while using FauxGravity.

How it works currently

My character jumps correctly when he is on top but when he is in the bottom of the sphere the jump doesn't take place.

Example

FauxGravityAttractor

[SerializeField] private float gravity = -9.81f;

public void Attract(Rigidbody body) {
    Vector3 gravityUp = (body.position - transform.position).normalized;
    Vector3 localUp = body.transform.up;
    
    // Apply downwards gravity to body
    body.AddForce(gravityUp * gravity);
    // Allign bodies up axis with the centre of planet
    body.rotation = Quaternion.FromToRotation(localUp,gravityUp) * body.rotation;
}

FauxGravityBody

FauxGravityAttractor planet;
new Rigidbody rigidbody;

void Awake()
{
    planet = GameObject.FindGameObjectWithTag("Planet").GetComponent<FauxGravityAttractor>();
    rigidbody = GetComponent<Rigidbody>();
    // Disable rigidbody gravity and rotation as this is simulated in GravityAttractor script
    rigidbody.useGravity = false;
    rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
}

void FixedUpdate()
{
    // Allow this body to be influenced by planet's gravity
    planet.Attract(rigidbody);
}

Sample Jumping

void Jump()
{
    if(Input.GetKeyDown(KeyCode.Space) && isOnGround)
    {
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        isOnGround = false;
    }
}

private void OnCollisionEnter(Collision collision)
{
    if(collision.gameObject.CompareTag("Planet"))
    {
        isOnGround = true;
    }
}

CodePudding user response:

FauxGravity jumping problem solved

All you need to do is AddRelativeForce to your rigidbody

Read more about RelativeForce

    // JUMPING
    private void Jump()
    {
        if (Input.GetKeyDown(KeyCode.Space) && onGround)
        {
            rb.AddRelativeForce(0, forceConst, 0, ForceMode.Impulse);
            onGround = false;
        }
    }
  • Related