LoginSignup
1

More than 5 years have passed since last update.

【Unity】ユニティちゃんの体の向きを滑らかに方向転回する

Last updated at Posted at 2018-12-02

環境メモ
⭐️Mac OS Mojave バージョン10.14
⭐️Unity 2018.2.15f1

ユニティちゃんの体の向きを滑らかに方向転回する。
矢印キーを押して向きを変えて走らせる。

完成系↓↓↓↓
forward.gif

1.「UnityChan」「Models」の「unitychan」をヒエラルキーウィンドウにDrag&Dropして配置する。
001.png

2.「Create」「Animator Controller」を選択し「UnityChanController」という名前にする
002.png

3.ヒエラルキーウィンドウの「unityChan」に「UnityChanController」をセットする
003.png

4.「UnityChanController」を開き、アニメータービューで右クリック「Create State」「Empty」を選択する
004.png

5.「 Empty」を「UnityChanWalk」に名前を変更する
Motion「RUN00_F」を選択する
005.png

6.Unity Chanが走る姿の状態となる。
run.gif

7.「DirectionScript.cs」を作成し、「unitychan」のコンポーネントに配置する
007.png

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

public class DirectionScript : MonoBehaviour {

    [SerializeField] float speed = 0.05f;
    [SerializeField] float smooth = 10f;

    // Update is called once per frame
    void Update () {
        // Horizontal 横方向移動に指定されたキー
        // Vertical 前後方向移動に指定されたキー
        // キーボードが押される
        Vector3 target = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        if (target.magnitude > 0.1)
        {
            //体の向きを滑らかに変更する
            Quaternion rotation = Quaternion.LookRotation(target);
            transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * smooth);
            //前方へ移動
            transform.Translate(Vector3.forward * Time.deltaTime * speed);
        }
        gameObject.transform.position += target * Time.deltaTime;
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1