using System.Collections; using System.Collections.Generic; using UnityEngine; public class AutoFlip : MonoBehaviour { [SerializeField] bool autoFlipX = false; [SerializeField] bool autoFlipY = false; [SerializeField] Camera referenceCamera; Vector2 screenPointOld; Vector2 direction = Vector2.zero; Vector2 directionOld = Vector2.zero; // Use this for initialization void Start () { if (referenceCamera == null) referenceCamera = FindObjectOfType().GetComponent().worldCamera; screenPointOld = referenceCamera.WorldToScreenPoint(transform.position); } int flipCounterX = 0; int flipCounterY = 0; // Update is called once per frame void Update () { if (referenceCamera == null) return; Vector2 screenPoint = referenceCamera.WorldToScreenPoint(transform.position); direction = screenPoint - screenPointOld; if (direction.x == 0) direction.x = directionOld.x; if (direction.y == 0) direction.y = directionOld.y; Quaternion rotation = transform.rotation; { //flip X if (direction.x * directionOld.x < 0) { flipCounterX = 1; } if (direction.x * directionOld.x > 0 && flipCounterX != 0) { flipCounterX += 1; } if (autoFlipX && flipCounterX >= 4) { rotation *= Quaternion.Euler(0, 180, 0); flipCounterX = 0; } } { //flip Y if (direction.y * directionOld.y < 0) { flipCounterY = 1; } if (direction.y * directionOld.y > 0 && flipCounterY != 0) { flipCounterY += 1; } if (autoFlipY && flipCounterY >= 4) { rotation *= Quaternion.Euler(180, 0, 0); flipCounterY = 0; } } transform.rotation = rotation; screenPointOld = screenPoint; directionOld = direction; /* if (direction.x != 0) directionOld.x = direction.x; if (direction.y != 0) directionOld.y = direction.y; */ } }