0
\$\begingroup\$

I'm trying to make a game object wrap around, so that as it exits through the right side of the screen it enters through left, and vice versa.

The code snippet below is what I'm working on.

Vector3 Pos = mainCam.WorldToScreenPoint(transform.position);
Vector3 LS  = mainCam.ScreenToWorldPoint(new Vector3(-1, 0f, 0f));
Vector3 RS  = mainCam.ScreenToWorldPoint(new Vector3(1, 0f, 0f));

if (Pos.x > Screen.width)
        transform.position = new Vector3(LS.x, transform.position.y, transform.position.z);

if (Pos.x < 0)
        transform.position = new Vector3(RS.x, transform.position.y, transform.position.z);

So far, exiting through the right and re-entering through left works, but the game object does not exit through the left side of the screen. There seems to be a barrier preventing it, or maybe my parameters for the second if statement are wrong.

\$\endgroup\$

3 Answers 3

1
\$\begingroup\$

It looks like you're trying to define LS & RS in normalized device coordinates (where -1 x is the left edge, +1 x is the right, and 0 z is the near plane):

Vector3 LS  = mainCam.ScreenToWorldPoint(new Vector3(-1, 0f, 0f));
Vector3 RS  = mainCam.ScreenToWorldPoint(new Vector3(1, 0f, 0f));

But Camera.ScreenToWorldPoint takes inputs in pixels (except for the z axis, which is measured in world units)

So when your character leaves the left side of the screen (their pixel coordinates' x value is less than 0) and you set them to the same x position as RS, you're moving them just about 1 pixel to the right - which is why it looks like they're not moving at all.

Instead you probably want something like this:

Vector3 LS  = mainCam.ScreenToWorldPoint(new Vector3(0, 0f, 1f));
Vector3 RS  = mainCam.ScreenToWorldPoint(new Vector3(mainCam.pixelWidth, 0f, 1f));

Note that I also increased the z component. This won't matter if you're using an orthographic camera, but if you ever switch to a perspective camera having a zero here will squash all outputs from ScreenToWorldPoint down to the camera position itself.

You may also want to add a little buffer or hysteresis here, so that the character doesn't visibly teleport back-and-forth, but has enough room to move fully off-screen and re-enter from the other side.

You might also want to use ViewportToWorldPoint, which works in coordinates normalized into the 0-1 range. The bottom-left of the viewport is (0,0); the top-right is (1,1).

\$\endgroup\$
0
\$\begingroup\$

If there is a barrier, it seems position.x should never be less than 0. Verify that the values from world to screen are not constrained and that there isnt a problem with actually moving the objects elsewhere.

\$\endgroup\$
0
\$\begingroup\$

In here:

Vector3 LS = mainCam.ScreenToWorldPoint(new Vector3(-1, 0f, 0f));

I imagine you ment to write:

Vector3 LS = mainCam.ScreenToWorldPoint(new Vector3(0, 0, 0));
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .