- Home /
How to re-position game object to the left side of the screen when it goes off the right side of the screen?
I am currently working on a portrait game and I'm trying to achieve something like the offscreen movement logic of the games Doodle Jump or Radical.
How do I re-position a game object to the left side of the screen when it goes off the right side of the screen and vice versa without being dependent of the screen size/aspect ratio?
Here's a snippet of code that I have right now:
void CheckBounds()
{
if (this.transform.position.x < -3.2f)
{
this.transform.position = new Vector3(3.2f, this.transform.position.y, this.transform.position.z);
}
if (this.transform.position.x > 3.2f)
{
this.transform.position = new Vector3(-3.2f, this.transform.position.y, this.transform.position.z);
}
}
void MovePlayer()
{
if (isFacingLeft)
{
this.transform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
}
else
{
this.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
}
}
Now this works but it's a dirty solution. As you can see I hard coded the bounds when the object goes offscreen which is +/- 3.2f.
This works perfectly on 16:9 aspect ratio devices but not on other aspect ratio devices.
How do I detect the screen edges to make this work regardless of the screen aspect ratio?
Thanks
You can use WorldToScreenPoint to check if an object is leaving the screen. Then you can wrap the object's position around in screen coordinates and use ScreenToWorldPoint to convert that point back to world coordinates.
Answer by LMan · Apr 07, 2015 at 02:30 AM
ViewportToWorldPoint might be quite simple. Convert 0 and 1 from viewport to world space and store the values of the axis you want to wrap in a variable in Start(). Then run a check every frame to see if the object's position is equal to or outside those points. if it is, set the appropriate axis to the appropriate point that you already saved. I do hope that makes sense. Good luck!