Kermer

Unity Borders Watcher

Nov 12th, 2018
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5.  
  6. public class BordersWatcher : MonoBehaviour {
  7.  
  8.    
  9.     private int maxLastValidPositionsCount = 5;
  10.     private float minDistanceBetweenPositions = 4.0f;
  11.    
  12.  
  13.     private CharacterController charController;
  14.     private bool isGrounded { get { return charController.isGrounded; } }
  15.     private Vector3 spawnPos;
  16.     private List<Vector3> lastValidPositions;
  17.     private Vector3? _teleportedFrom;
  18.  
  19.     // Use this for initialization
  20.     void Start () {
  21.         spawnPos = transform.position;
  22.         charController = GetComponent<CharacterController>();
  23.         lastValidPositions = new List<Vector3>();
  24.         InvokeRepeating("ValidateFloor", 5.0f, 1.0f);
  25.     }
  26.    
  27.     // Update is called once per frame
  28.     void Update () {
  29.         if (isOutOfMap())
  30.         {
  31.             TeleportBack();
  32.         }
  33.     }
  34.  
  35.     bool isOutOfMap()
  36.     {
  37.         return transform.position.y < -50;
  38.     }
  39.  
  40.     void ValidateFloor()
  41.     {
  42.         if (isGrounded)
  43.         {
  44.             while (lastValidPositions.Count >= maxLastValidPositionsCount)
  45.                 lastValidPositions.RemoveAt(0);
  46.            
  47.             if (lastValidPositions.Count > 0 || _teleportedFrom.HasValue)
  48.             {
  49.                 Vector3 lastPos = _teleportedFrom ?? lastValidPositions.Last();
  50.                 if (Vector3.Distance(lastPos, transform.position) < minDistanceBetweenPositions)
  51.                     return;
  52.             }
  53.             lastValidPositions.Add(transform.position);
  54.             _teleportedFrom = null;
  55.         }
  56.     }
  57.  
  58.     void TeleportBack()
  59.     {
  60.         Vector3 targetPos = spawnPos;
  61.         if (lastValidPositions.Count > 0)
  62.         {
  63.             targetPos = lastValidPositions.Last();
  64.             lastValidPositions.Remove(targetPos);
  65.         }
  66.         transform.position = targetPos + new Vector3(0,0.01f);
  67.         _teleportedFrom = targetPos;
  68.     }
  69.    
  70. }
Add Comment
Please, Sign In to add comment