Skip to content

Instantly share code, notes, and snippets.

@omid3098
Last active March 19, 2019 11:07
Show Gist options
  • Save omid3098/0ab434989e92a8c7fa5121af5a7b707d to your computer and use it in GitHub Desktop.
Save omid3098/0ab434989e92a8c7fa5121af5a7b707d to your computer and use it in GitHub Desktop.
Simple eye follow for unity using DoTween for blink (you can comment them if you dont want to blink with tween)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class EyeFollow : MonoBehaviour
{
[SerializeField] Transform[] insideEyes;
[SerializeField] float EyeRadius;
[SerializeField] int updateInterval = 3;
[Tooltip("Set target for eyes use null to follow mouse/touch")]
[SerializeField] Transform target;
private Camera _camera;
private float randomBlinkTime;
private float ellapsedTime;
private float startScaleY;
private bool centered;
private void Awake()
{
_camera = Camera.main;
randomBlinkTime = Random.Range(1f, 4f);
ellapsedTime = 0;
startScaleY = transform.localScale.y;
}
public void SetTarget(Transform target)
{
this.target = target;
}
void Update()
{
ellapsedTime += Time.deltaTime;
if (hasInput)
{
if (Time.frameCount % updateInterval == 0)
{
centered = false;
foreach (var insideEye in insideEyes)
insideEye.localPosition = EyeRadius * (targetPosition - insideEye.position).normalized;
}
}
else if (releaseInput)
{
if (!centered)
{
centered = true;
foreach (var insideEye in insideEyes)
insideEye.localPosition = Vector3.zero;
}
}
if (ellapsedTime > randomBlinkTime)
{
ellapsedTime = 0;
randomBlinkTime = Random.Range(1f, 4f);
var tween = transform.DOScaleY(0, 0.05f);
tween.onComplete += () =>
{
var scaleUpTween = transform.DOScaleY(startScaleY, 0.3f);
scaleUpTween.SetEase(Ease.OutQuart);
};
}
}
private Vector3 targetPosition
{
get
{
if (target != null) return target.position;
#if UNITY_EDITOR || UNITY_STANDALONE
return _camera.ScreenToWorldPoint(Input.mousePosition);
#elif UNITY_ANDROID || UNITY_IOS
if (Input.touchCount > 0) return _camera.ScreenToWorldPoint(Input.GetTouch(0).position);
else return Vector3.zero;
#endif
}
}
private bool hasInput
{
get
{
if (target != null) return true;
#if UNITY_EDITOR || UNITY_STANDALONE
return Input.GetMouseButton(0);
#elif UNITY_ANDROID || UNITY_IOS
return Input.touchCount > 0;
#endif
}
}
private static bool releaseInput
{
get
{
#if UNITY_EDITOR || UNITY_STANDALONE
return Input.GetMouseButtonUp(0);
#elif UNITY_ANDROID || UNITY_IOS
return Input.touchCount == 0;
#endif
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment