Achieving an Asteroids-style screen wrap

Hi all, I’ve searched through and I can see this has been asked multiple times but none of them had an answer that I could actually make sense of. I’m a C# rookie, and I’m trying to achieve what they’ve got going on in Unitroids (link: The Scripting Reference has this example for the Mathf.Repeat function:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    void Update() {
        transform.position = new Vector3(Mathf.Repeat(Time.time, 3), transform.position.y, transform.position.z);

But this just makes the object slide off to the side and then repeat after a certain amount of time (I think?) and I want it to repeat after hitting the edge of the screen, not time. In the Unitroids thread Eric said that the wrap code they used was:

            myTransform.position.x = Mathf.Repeat(myTransform.position.x, aWidth);
            myTransform.position.z = Mathf.Repeat(myTransform.position.z, aHeight);

But I can’t make that code work, I’ve really no idea how to even read it!

Any assistance would be really appreciated, and sorry for such a lengthy post!


That code snippet you have actually solves your problem. Let me help you read it.

myTransform.position.x = Mathf.Repeat(myTransform.position.x, aWidth);

myTransform.position.x reffers to the x coordinate of your object.

aWidth is the width of the play area. So its the size of the area you want to wrap. If you want to wrap everything, just make this something thats slightly larger than your visible area.

Mathf.Repeat() makes sure you dont go over the bounds of your defined area. So if you have Mathf.Repeat(2.1, 2) the function returns 0.1. Meaning, if your asteroid flies outside your size 2.0 play area, it gets moved to the start, ie 0.1.

The code snippet you have is done separately for both x and z (in a top-down view) coordinates. So each time your asteroid goes out of bounds, it pops up at the other end. I hope that clears something up.