Weird bug that seemingly contradicts code

Hello,

I am having a problem with the wrapping. I have separated the wrapping code into a class of its own with the intention of putting it on the asteroids as well. The problem I’m having is when the viewport.y is > 0. The transform.position is set ok but then it ends up somehow below the bottow edge of the screen, and so gets moved to the top while moving upward, which prompts another move to the bottom below the edge and just gets teleported to the top moving up again, and so on. It only does this for moving off the top edge of the screen, upwards. There is no other code in any script affecting wrapping or the transform.position.

using UnityEngine;

public class ScreenWrapMovement : MonoBehaviour
{
    void Update()
    {
        KeepPlayerOnScreen();
    }
    private void KeepPlayerOnScreen()
    {
        Vector3 newPosition = transform.position;

        Vector3 viewportPosition = Camera.main.WorldToViewportPoint(newPosition);
        
        if (viewportPosition.x > 1)
        {   
            newPosition.x = -newPosition.x + 1f;
        }
        else if (viewportPosition.x < 0) 
        {   
            newPosition.x = -newPosition.x - 1f;
        }
        
        if (viewportPosition.y > 1)
        {    
            newPosition.y = -newPosition.y + 1f;
        }
        else if (viewportPosition.y < 0)
        {
            newPosition.y = -newPosition.y - 1f;
        }

        transform.position = newPosition;
    }
}

I have no idea what I’m doing wrong and would appreciate some assistance.

Thanks in advance,
W

I don’t know if this is the issue, but the above code will only work as expected if the world origin (0,0) is exactly in the middle of the screen.

1 Like

The offset of each wrap was too small. I increased the 1 to a 5 and it works brilliantly.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms