Search Unity

How to rotate single bone in script while playing 2D skeletal animation?

Discussion in '2D' started by aksik_, Mar 10, 2021.

  1. aksik_

    aksik_

    Joined:
    Sep 14, 2020
    Posts:
    3
    Hi, I'm tring to make an animation in which enemy shoots player. Of course player will be moving on the map, so I can't make static hand rotation in animation as I can't access player position there.
    When I change bone rotation in script (in event function called from animation / Update / LateUpdate), the rotation doesn't apply, despite I'm not even changing that bone rotation in animation (I do change it's position).

    So is there any way to change that rotation outside animation? Or maybe there is a possibility to pass a parameter to animation that tells how much to rotate bone?

    Also I've found this solution but it's based on "animation" variable which if I understand correctly is GetComponent<Animation>(). I'm using animator for animating characters so can I access the "animation" somehow?

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class MyAnimationController : MonoBehaviour
    4. {
    5.     [SerializeField] private Transform _rightHand;
    6.     [SerializeField] private Transform _leftHand;
    7.     private EnemyController _enemyController;
    8.     private Quaternion _leftHandRotation;
    9.     private Quaternion _rightHandRotation;
    10.     void Start()
    11.     {
    12.         _enemyController = GetComponentInParent<EnemyController>();
    13.     }
    14.  
    15.     public void RightHandAimPlayer() // event called from animation
    16.     {
    17.         var vector = _enemyController.Player.transform.position - _rightHand.transform.position;
    18.         _rightHandRotation = Quaternion.LookRotation(vector, Vector3.back);
    19.         _rightHand.rotation = _rightHandRotation;
    20.     }
    21.     public void LeftHandAimPlayer() // event called from animation
    22.     {
    23.         var vector = _enemyController.Player.transform.position - _leftHand.transform.position;
    24.         _leftHandRotation = Quaternion.LookRotation(vector, Vector3.back);
    25.         _leftHand.rotation = _leftHandRotation;
    26.     }
    27.     private void LateUpdate()
    28.     {
    29.         _leftHand.rotation = _leftHandRotation;
    30.         _rightHand.rotation = _rightHandRotation;
    31.     }
    32. }
     
  2. Remaust

    Remaust

    Joined:
    Oct 2, 2021
    Posts:
    1
    You can use Animator.SetFloat() to pass a float to the animator, but, as far as I know, you cannot pass a Quaternion to the animator.
    Also, this might help.

    Hope my answer helps you!