Unity C# Script for Player Grinding on a Spline

 avatar
unknown
csharp
a year ago
2.2 kB
15
Indexable
private void FixedUpdate()
{
    if (isGrinding)
    {
        if (isReversing)
        {
            splineProgress -= grindSpeed * Time.fixedDeltaTime;
        }
        else
        {
            splineProgress += grindSpeed * Time.fixedDeltaTime;
        }

        splineProgress = Mathf.Clamp01(splineProgress);

        Vector3 railPosition = currentSpline.EvaluatePosition(splineProgress);
        playerPhysics.RB.MovePosition(railPosition);

        Vector3 tangent = math.normalize(currentSpline.EvaluateTangent(splineProgress));
        playerPhysics.RB.MoveRotation(Quaternion.LookRotation(tangent));

        grindVelocity = (railPosition - previousPosition) / Time.fixedDeltaTime;
        previousPosition = railPosition;

        if (splineProgress <= 0f || splineProgress >= 1f)
        {
            ExitGrind();
        }
    }
}

public void ExitGrind()
{
    isGrinding = false;

    // Calculate exit velocity based on rail's direction and speed
    Vector3 exitTangent = math.normalize(currentSpline.EvaluateTangent(splineProgress));
    Vector3 exitDirection = isReversing ? -exitTangent : exitTangent;
    playerPhysics.RB.velocity = (exitDirection * grindSpeed) + playerPhysics.verticalVelocity;

    currentSpline = null;
    playerPhysics.DisableGroundCheck = false;
    
    moveAction.enabled = true;
    animator.SetBool(GrindingHash, false);
    animator.ResetTrigger(LandOnRailHash);

    if (risingAndFalling != null)
    {
        risingAndFalling.IsAnimationOverridden = false;
    }

    if (playerModel != null)
    {
        playerModel.localPosition = initialModelLocalPosition;
    }
}

private void OnTriggerEnter(Collider other)
{
    SplineContainer spline = other.GetComponent<SplineContainer>();
    if (spline != null && other is MeshCollider)
    {
        RailProperties railProperties = other.GetComponent<RailProperties>();
        if (railProperties != null)
        {
            grindSpeed = railProperties.grindSpeed;
        }
        else
        {
            grindSpeed = minGrindSpeed;
        }
        
        StartGrind(spline);
    }
}
Editor is loading...
Leave a Comment