Unity アニメーション中に、StateMachineBehaviourを使って、オブジェクトを移動

Unity

説明

Unityでアニメーションは、デフォルト設定のままでは、オブジェクトは移動しません。
例えば、以下のようにユニティちゃんが前方にスクリューキックをしても、元の位置に戻ってしまします。

今回は、上記の「HQ Fighting Animation FREE」のユニティちゃんがスクリューキックした際に、元の位置に戻ってしまう問題を解決していきます。

下準備

①. こちらのサイトを参考にして、シーンにユニティちゃんを設置してください。
ユニティちゃんを設置する」まで行ってください。(顔・CharacterControllerの設置まで)

②. ユニティちゃんのオブジェクトにAttack.csという以下のスクリプトをAdd Componentして、Zキーを押したときに、スクリューキックをできるようにします。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Attack : MonoBehaviour {
 
    //PlayerのAnimatorコンポーネント保存用
    private Animator animator;
    private string parameterName = "Jab";

    private bool actionFlag = false;
 
	// Use this for initialization
	void Start () {
        //PlayerのAnimatorコンポーネントを取得する
        animator = GetComponent<Animator>();
	}
	
	// Update is called once per frame
	void Update () {
		
       if(Input.GetKey(KeyCode.Z)){
            //Aを押すとjab
            actionFlag = true;
            parameterName = "ScrewK";
        }
        else if (Input.GetKey(KeyCode.X))
        {
            //Sを押すとHikick
            actionFlag = true;
            parameterName = "Hikick";
        }
        else
        {
            actionFlag = false;
        }

        animator = GetComponent<Animator>();
        animator.SetBool(parameterName, actionFlag); 
	}
}

アニメーション中にオブジェクトを移動させる

今回は、アニメーション中にオブジェクトを移動させることで、元の位置にオブジェクトが戻らないようにします。

①. Window→Animation→Animatorで、Animatorでウインドウを開きます。

②. ScrewKickを選択して、Inspectorで「Add Behabiour」で新規に「ScrewKBehaiviour」を作ります。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScrewKBehaiviour : StateMachineBehaviour
{
	public float Speed = 5f;
    private CharacterController characterController;
	
	override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) 
	{
		characterController = animator.GetComponent<CharacterController>();
		characterController.Move(animator.gameObject.transform.forward * Speed * Time.deltaTime);
	}
	
}

③. 実行して、確認

コメント

タイトルとURLをコピーしました