Source file unity-csharp/arcade-classics/asteroids/ScreenWrap2D.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: a reusable screen-wrap component shared by the ship, bullets, and asteroids
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[unity-transform]]
 
using UnityEngine;
 
// Drop this on anything that should reappear on the opposite edge when it leaves
// the screen. Writing it once as its own component — rather than copying the
// logic into every mover — is the small architecture lesson of this step.
public class ScreenWrap2D : MonoBehaviour
{
    private Camera cachedCamera;
    private float margin;
 
    private void Awake()
    {
        cachedCamera = Camera.main;
        SpriteRenderer sprite = GetComponent<SpriteRenderer>();
        // Wrap only once the object is fully off-screen, so it slides off and back.
        margin = sprite != null ? sprite.bounds.extents.magnitude : 0.5f;
    }
 
    // LateUpdate runs after movement, so we wrap the final position for the frame.
    private void LateUpdate()
    {
        float halfHeight = cachedCamera.orthographicSize;
        float halfWidth = halfHeight * cachedCamera.aspect;
        Vector3 position = transform.position;
 
        if (position.x > halfWidth + margin)
        {
            position.x = -halfWidth - margin;
        }
        else if (position.x < -halfWidth - margin)
        {
            position.x = halfWidth + margin;
        }
 
        if (position.y > halfHeight + margin)
        {
            position.y = -halfHeight - margin;
        }
        else if (position.y < -halfHeight - margin)
        {
            position.y = halfHeight + margin;
        }
 
        transform.position = position;
    }
}