I'm working on a very simple endless runner, tracks are generated in a straight line, one on the end of each, the player simply runs towards the Z axis. Every attempt I've made to reset the origin point ends the same way, the player falls to infinity. The track is ripped from under the player, and whatever track pieces are generated move towards infinity.
I've done this so many times, so many iterations, but here's my latest attempt. This script is attached to the player's GameObject.
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
[RequireComponent(typeof(Camera))]
public class FloatingOrigin : MonoBehaviour
{
public float threshold = 500.0f;
[SerializeField]
void LateUpdate()
{
if (Mathf.Abs(transform.position.z) > threshold)
{
ResetWorldPosition();
}
}
private void ResetWorldPosition()
{
// Store the current position of the player
Vector3 playerOffset = transform.position;
// Iterate through all root objects of all scenes
for (int i = 0; i < SceneManager.sceneCount; i++)
{
Scene scene = SceneManager.GetSceneAt(i);
foreach (GameObject root in scene.GetRootGameObjects())
{
// Skip the player root
if (root.transform == transform) continue;
// Move the object by the offset
root.transform.position -= playerOffset;
}
}
// Move the player to the origin
transform.position = new Vector3(0, 0.6f, 0);
}
}
Why is the track moving to infinity? Track pieces get generated when a trigger in the middle of a track is hit, and 3 tracks can be loaded max. When the tracks are moving to infinity, I believe they are not loading/unloading, and are just getting transformed.
I've recently tried this version of ResetWorldPosition, and the result was the same.
private void ResetWorldPosition()
{
var currentScene = SceneManager.GetActiveScene();
var rootObjects = currentScene.GetRootGameObjects();
foreach (var root in rootObjects)
{
if (root == transform.root) continue;
root.transform.SetParent(transform);
}
transform.position = Vector3.zero;
foreach (var root in rootObjects)
{
if (root == transform.root) continue;
root.transform.SetParent(null);
}
}
What is so ridiculous, is that there is no vector math to mess this one up, I'm making children parents of the player and resetting the player to zero... the track goes to infinity.