Search Unity

  1. Are you interested in providing feedback directly to Unity teams? Sign up to become a member of Unity Pulse, our new product feedback and research community.
    Dismiss Notice

Help Wanted How can I set the distance the player will look at the target using IK ?

Discussion in 'Scripting' started by shamenraze1988, Jul 17, 2021.

  1. shamenraze1988

    shamenraze1988

    Joined:
    Nov 24, 2020
    Posts:
    208
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. [RequireComponent(typeof(Animator))]
    4.  
    5. public class LookAtIKController : MonoBehaviour
    6. {
    7.     public Transform lookObj = null;
    8.     public float finalLookWeight;
    9.     public float weightDamping = 1.5f;
    10.  
    11.     protected Animator animator;
    12.  
    13.     void Start()
    14.     {
    15.         animator = GetComponent<Animator>();
    16.     }
    17.  
    18.     //a callback for calculating IK
    19.     void OnAnimatorIK()
    20.     {
    21.         if (lookObj != null)
    22.         {
    23.             Vector3 flattenedLookAtVector = Vector3.ProjectOnPlane(lookObj.position - transform.position, transform.up);
    24.             float dotProduct = Vector3.Dot(transform.forward, flattenedLookAtVector);
    25.             float lookWeight = Mathf.Clamp(dotProduct, 0f, 1f);
    26.             finalLookWeight = Mathf.Lerp(finalLookWeight, lookWeight, Time.deltaTime * weightDamping);
    27.             float bodyWeight = finalLookWeight * .5f;
    28.  
    29.             animator.SetLookAtWeight(finalLookWeight, bodyWeight);
    30.             animator.SetLookAtPosition(lookObj.position);
    31.         }
    32.     }
    33. }
    34.  
    It's working fine when the player is getting very close to the lookObj but how can I add some public float variable that will set the distance the player will look at the lookObj from?
     
  2. TheFunnySide

    TheFunnySide

    Joined:
    Nov 17, 2018
    Posts:
    112
    Code (CSharp):
    1. float distance = Vector3.Distance(lookObj.position - transform.position)
    2.  
    3. if(distance < cutOffValue)
    4. {
    5. //stuff
    6. }
    Honestly you might replace this complicated code you have with a bunch of curves where you insert distance and angles.

    But then again i havent done this kind of stuff myself
     
unityunity