Player keeps teleporting between two positions back and forth when leaving the screen

So I’m recreating 199404-shiphelp.png

However if the player leaves like this, the ship starts teleporting back and forth between two opposite positions 199406-screenshot-2022-09-01-134058.png
I made a video to better demonstrate the problem

Here’s my code:

public void transport()
    {
        Vector3 stageDimensions = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0));

        if (transform.position.x > stageDimensions.x)
        {
            transform.position = new Vector2((-transform.position.x), transform.position.y);
        }
        else if (transform.position.x < -(stageDimensions.x))
        {
            transform.position = new Vector2(Mathf.Abs(transform.position.x), transform.position.y);

        }

        if (transform.position.y > stageDimensions.y)
        {
            transform.position = new Vector2(transform.position.x, (-transform.position.y));
        }
        else if (transform.position.y < -(stageDimensions.y))
        {
            transform.position = new Vector2(transform.position.x, Mathf.Abs(transform.position.y));

        }

    }

Is there a way to fix this problem? Any help will be appreciated. Thank you in advance!

The problem is here

if(transform.position.x > stageDimensions.x)
{
	transform.position = new Vector2((-transform.position.x), transform.position.y);
}
else if(transform.position.x < -(stageDimensions.x))
{
	transform.position = new Vector2(Mathf.Abs(transform.position.x), transform.position.y);
}

When transform.position.x > stageDimensions.x, it will set transform.position.x to -transform.position.x which will still be less than -stageDimensions.x and out of screen. The same will happen if transform.position.x < -stageDimensions.x, transform.position.y > stageDimensions.y and transform.position.y < -stageDimensions.y. What you can do is add some offset to transform.position so your player is inside the screen, so something like

public float offsetX = 2f;
public float offsetY = 2f;

public void transport()
{
	Vector3 stageDimensions = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0));

	if(transform.position.x > stageDimensions.x)
	{
		transform.position = new Vector2(-(stageDimensions.x) + offsetX, transform.position.y);
	}
	else if(transform.position.x < -(stageDimensions.x))
	{
		transform.position = new Vector2(stageDimensions.x - offsetX, transform.position.y);
 
	}

	if(transform.position.y > stageDimensions.y)
	{
		transform.position = new Vector2(transform.position.x, -(stageDimensions.y) + offsetY);
	}
	else if(transform.position.y < -(stageDimensions.y))
	{
		transform.position = new Vector2(transform.position.x, stageDimensions.y - offsetY);
	}
}

Do you want the player to go from one side to the other side horizontally?