Friday, May 9, 2014

Preventing float overflow on endless runner type of game

If the character is moving against the world, instead of the world moving against the player also known as treadmill-type mechanism, there's a likely chance that the player's location could overflow the float's limitation.


Here's a way to deal with that problem:

using UnityEngine;
using System.Collections;

public class CameraRunnerScript : MonoBehaviour {

    public Transform player;

    // Update is called once per frame
    void Update () 
    {
        MoveCamera ();

        float currentCameraX = this.transform.position.x;

        // this prevents overflowing the float, reset the camera
        if (currentCameraX > 100) 
        {
            // reset the player position
            this.player.transform.position = new Vector3(0, player.position.y, 0);


            MoveCamera ();      


            // make all spawned object follow the camera's new position
            var grounds = GameObject.FindGameObjectsWithTag("Ground");
            foreach (var item in grounds) 
            {
                var delta = item.transform.position.x - currentCameraX;
                item.transform.position = new Vector3(this.transform.position.x + delta, item.transform.position.y, 0);
            }


        }
    }


    // move the camera based on player's position
    void MoveCamera ()
    {
        this.transform.position = new Vector3 (this.player.position.x + 6, 0, -10);
    }


}

No comments:

Post a Comment