Switch statement only working on first case?

hey, so i have this script attached to a conveyor belt in my game, it looks like this.

void OnCollisionStay2D(Collision2D collision)
    {
        UnityEngine.Transform Collided = collision.gameObject.transform;
       
        switch(transform.rotation.z)
        {
            case 0:
                Collided.position = new Vector3(Collided.position.x,Collided.position.y + speed,Collided.position.z);
                break;
            case 90:
                Collided.position = new Vector3(Collided.position.x + speed,Collided.position.y,Collided.position.z);
                break;
            case -180:
                Collided.position = new Vector3(Collided.position.x,Collided.position.y - speed,Collided.position.z);
                break;
            case -90:
                Collided.position = new Vector3(Collided.position.x - speed,Collided.position.y,Collided.position.z);
                break;

        }


    }

but it only works when the conveyor is pointing upwards (z = 0). im new to switch statements so i might have done something wrong. help is much apreciated.

So you’re using a switch statement, and you’re comparing a float (the rotation z value) to all these numbers. Float comparison is notoriously bad to do, as it has weird unexpected behaviors, and as you can tell, won’t return true even if it looks true. One thing you could do to offset this, is to round the value, so it would look something like switch(Mathf.Round(transform.rotation.z)) and use that to check.

okay, that makes sense. thank you

Also, don’t use the Transform as that’s for rendering. The Rigidbody2D is the authoritative state of the pose here for XY position and Z rotation. Use that because they won’t be the same if interpolation is involved either.

1 Like

Another big problem you have, in addition to everything said above, is that transform.rotation.z is a quaternion component and will only ever be in the range -1 to 1. There will be no 90, 180, or -90 values for it. Nor does the z component of the quaternion directly correspond to the rotation of the object around the Z axis.

1 Like

thank you so much, i will now go on a quest to destroy the devil who i can only assume to be a four dimensional way of describing direction in a 3D space.

1 Like