Search code examples
unity-game-enginerotationpositioncollision-detectionraycasting

Unity OnCollisionExit() not working


I have a player object and a ramp called StartRamp. I am using the code below to change my players position and rotation to the surface off the ramp. When my player is off the ramp I want to change the player rotation in the x axis to be only between 50,-50.

But my else statement for when surface is false is not running. Which makes me think my OnCollisionExit() is wrong. Can someone help me?

Script with following code is attached to player object

private void OnCollisionStay(Collision collision)
{
    if(collision.gameObject.name == "StartRamp"){
        surface = true;
    }
}
private void OnCollisionExit(Collision collision)
{
    if (collision.gameObject.name != "StartRamp")
    {
        surface = false;
    }
}

public void playerToSurface(){

    if (surface == true){ // Change Position When On Ramp

        Ray ray = new Ray(transform.position, -transform.up);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 1.5f) == true)
        {
            Debug.DrawLine(transform.position, hit.point, Color.green);
            rotCur = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
            posCur = new Vector3(transform.position.x, hit.point.y, transform.position.z);
            grounded = true;
        }
        else
        {
            grounded = false;
        }
        if (grounded == true)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, rotCur, Time.deltaTime * 5);
        }
        else
        {
            transform.position = Vector3.Lerp(transform.position, transform.position - Vector3.up * 1f, Time.deltaTime * 5);
        }

    }else{ // Change Position When Off Ramp

        Debug.Log("Player is off ramp.\n");

    }
}

// Update player position to ground
private void Update()
{
    playerToSurface();
}

Solution

  • Since OnCollisionExit is looking for the collider you are no longer in contact with, not any ones you aren't, you should say that the object name is startramp, not isn't.

    private void OnCollisionExit(Collision collision)
    {
    if (collision.gameObject.name == "StartRamp")
        {
            surface = false;
        }
    }