using System.Collections; using System.Collections.Generic; using UnityEngine; public class Follower_Script : MonoBehaviour { GameObject player; Player_Move_Script moveScript; private Queue states = new Queue(); public int playerLayer = 8; private float width; private float height; // Start is called before the first frame update void Start() { player = GameObject.FindGameObjectWithTag("Player"); moveScript = player.GetComponent(); width = GetComponent().bounds.size.x; height = GetComponent().bounds.size.y; } // Update is called once per frame void Update() { if (Static_GlobalStats.paused) { float x = player.transform.position.x + (-player.transform.localScale.x * width * 1.15f); x = (transform.position.x + x) / 2; float y = (transform.position.y + player.transform.position.y) / 2; transform.position = new Vector2(x, y); GetComponent().SetFloat("speed", 0); GetComponent().SetBool("grounded", true); return; } if (Mathf.Abs(moveScript.speed) > 0.1f || player.GetComponent().grounded == false) { states.Enqueue(new PlayerState(player)); } int layerMask = ~(1 << playerLayer); RaycastHit2D groundHit = Physics2D.Raycast(transform.position, Vector2.down, height * 0.6f, layerMask); if (states.Count > 48 || (!groundHit.collider && states.Count > 0)) { PlayerState state = states.Dequeue(); transform.position = state.position; transform.localScale = new Vector2(state.speed == 0 ? transform.localScale.x : Mathf.Abs(state.speed) / state.speed, transform.localScale.y); GetComponent().SetFloat("speed", Mathf.Abs(state.speed)); GetComponent().SetBool("grounded", state.grounded); } else if (!groundHit.collider) { float x = player.transform.position.x + (-player.transform.localScale.x * width * 1.15f); x = (transform.position.x + x) / 2; float y = (transform.position.y + player.transform.position.y) / 2; y -= 0.2f; transform.position = new Vector2(x, y); GetComponent().SetFloat("speed", 0); GetComponent().SetBool("grounded", true); } else { GetComponent().SetFloat("speed", 0); GetComponent().SetBool("grounded", groundHit.collider != null); } } private class PlayerState { public Vector2 position; public float speed; public bool grounded; public PlayerState(GameObject player) { position = new Vector2(player.transform.position.x, player.transform.position.y); speed = player.GetComponent().speed; grounded = player.GetComponent().grounded; } } }