简体   繁体   中英

How to fix negative magnitude in 2D Unity project

I've build a simple 2D project in Unity and trying to implement kinematic physics. I'm getting negative magnitude for moving vector, and i want to know why.

图片

The collider right on the edge of walls, but i don't understand how exactly it can affect a private variable

Move method called in FixedUpdate

private void Move(Vector2 destination)
{
    // destination: "(0.0, -0.1)"

    float distance = destination.magnitude;
    // destination: "(0.0, -0.1)"   distance: -0.00999999978

    if (distance > MinMoveDistance)
    {
        int count = rigidbody2D.Cast(destination, hitBuffer, distance + ShellRadius);

        for (int i = 0; i < count; i++) 
        {
            Vector2 currentNormal = hitBuffer[i].normal;

            if (Mathf.Approximately(currentNormal.y, 1f)) 
            {
                IsGrounded = true;
            }

            float modifiedDistance = hitBuffer[i].distance - ShellRadius;

            distance = modifiedDistance < distance ? modifiedDistance : distance;
        }
    }

    rigidbody2D.position = rigidbody2D.position + destination.normalized * distance;
}

float distance = destination.magnitude; should always return a positive number, not sure how you are getting the values you have provided in your comments.

Regardless, if you want to ensure that distance is always positive, simply use float distance = Mathf.Abs(destination.magnitude);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM