- Home /
IK LookAt Smoothly change between targets and problem with offseting the "Scan area"
Hey there,
I would like to do a smooth change between the objects the player is looking at. For example if he collected the object he looket at and then he looks to the other one.
If this could be solved it would be great!
The other problem is I want to offset the area he's scanning for objects to look at. I couldn't manage it to work properly... I just don't want him to turn his head behind.
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Animator))]
public class IKControl : MonoBehaviour
{
public Transform lookObject;
float lookRadius = 10;
Animator anim;
public float animWeight;
public bool turnHeadLookOn;
GameObject LookAtObject;
public GameObject closestTarget;
public float curDistance;
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position + transform.forward * 10, lookRadius);
}
void Start()
{
anim = GetComponent<Animator>();
}
void FixedUpdate()
{
if (turnHeadLookOn)
{
animWeight = Mathf.SmoothStep(animWeight, 1, Time.deltaTime * 10);
if (animWeight > 0.95f)
{
animWeight = 1;
}
}
else
{
animWeight = Mathf.SmoothStep(animWeight, 0, Time.deltaTime * 10);
if (animWeight < 0.05f)
{
animWeight = 0;
}
}
FindClosestEnemy();
}
void FindClosestEnemy()
{
float distanceToClosestEnemy = Mathf.Infinity;
GameObject closestEnemy = null;
GameObject[] allEnemies = GameObject.FindGameObjectsWithTag("spawn");
foreach (GameObject currentEnemy in allEnemies)
{
float distanceToEnemy = (currentEnemy.transform.position - this.transform.position + -transform.forward * 10).sqrMagnitude;
if (distanceToEnemy < distanceToClosestEnemy)
{
distanceToClosestEnemy = distanceToEnemy;
closestEnemy = currentEnemy;
}
}
Vector3 dist = this.transform.position + transform.forward * 10 - closestEnemy.transform.position;
curDistance = dist.magnitude;
LookAtObject = closestEnemy;
lookObject.position = Vector3.Lerp(lookObject.position, LookAtObject.transform.position, .2f);
Debug.DrawLine(this.transform.position, closestEnemy.transform.position, Color.red);
if(curDistance <= lookRadius)
{
turnHeadLookOn = true;
}else if (curDistance > lookRadius)
{
turnHeadLookOn = false;
}
}
void OnAnimatorIK()
{
if (turnHeadLookOn && closestTarget != null)
{
anim.SetLookAtWeight(animWeight, 0f, 0.5f, 0f);
anim.SetLookAtPosition(lookObject.transform.position);
}
else
{
anim.SetLookAtWeight(animWeight, 0f, 0.5f, 0f);
anim.SetLookAtPosition(lookObject.transform.position);
}
}
}
Thanks for reading.
Your answer
Follow this Question
Related Questions
Animated mesh looking the wrong way when using SetLookAtPosition 1 Answer
How can I use IK with AnimationClipPlayable or AnimationMixerPlayable? 1 Answer
How to have SetLookAtPosition for head and body differently? 0 Answers
Animation with bones, Limb Solver knee is bending in wrong way 1 Answer
Switch Weapon using Animation 1 Answer