Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- public class BordersWatcher : MonoBehaviour {
- private int maxLastValidPositionsCount = 5;
- private float minDistanceBetweenPositions = 4.0f;
- private CharacterController charController;
- private bool isGrounded { get { return charController.isGrounded; } }
- private Vector3 spawnPos;
- private List<Vector3> lastValidPositions;
- private Vector3? _teleportedFrom;
- // Use this for initialization
- void Start () {
- spawnPos = transform.position;
- charController = GetComponent<CharacterController>();
- lastValidPositions = new List<Vector3>();
- InvokeRepeating("ValidateFloor", 5.0f, 1.0f);
- }
- // Update is called once per frame
- void Update () {
- if (isOutOfMap())
- {
- TeleportBack();
- }
- }
- bool isOutOfMap()
- {
- return transform.position.y < -50;
- }
- void ValidateFloor()
- {
- if (isGrounded)
- {
- while (lastValidPositions.Count >= maxLastValidPositionsCount)
- lastValidPositions.RemoveAt(0);
- if (lastValidPositions.Count > 0 || _teleportedFrom.HasValue)
- {
- Vector3 lastPos = _teleportedFrom ?? lastValidPositions.Last();
- if (Vector3.Distance(lastPos, transform.position) < minDistanceBetweenPositions)
- return;
- }
- lastValidPositions.Add(transform.position);
- _teleportedFrom = null;
- }
- }
- void TeleportBack()
- {
- Vector3 targetPos = spawnPos;
- if (lastValidPositions.Count > 0)
- {
- targetPos = lastValidPositions.Last();
- lastValidPositions.Remove(targetPos);
- }
- transform.position = targetPos + new Vector3(0,0.01f);
- _teleportedFrom = targetPos;
- }
- }
Add Comment
Please, Sign In to add comment