12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Follower_Script : MonoBehaviour
- {
- GameObject player;
- Player_Move_Script moveScript;
- private Queue<PlayerState> states = new Queue<PlayerState>();
- 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<Player_Move_Script>();
-
- width = GetComponent<SpriteRenderer>().bounds.size.x;
- height = GetComponent<SpriteRenderer>().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<Animator>().SetFloat("speed", 0);
- GetComponent<Animator>().SetBool("grounded", true);
-
- return;
- }
- if (Mathf.Abs(moveScript.speed) > 0.1f || player.GetComponent<Player_Move_Script>().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<Animator>().SetFloat("speed", Mathf.Abs(state.speed));
- GetComponent<Animator>().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<Animator>().SetFloat("speed", 0);
- GetComponent<Animator>().SetBool("grounded", true);
- }
- else {
- GetComponent<Animator>().SetFloat("speed", 0);
- GetComponent<Animator>().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<Player_Move_Script>().speed;
- grounded = player.GetComponent<Player_Move_Script>().grounded;
- }
- }
- }
|