ブログ

(Unity)人型のキャラクターをシンプルに動かす

(構成&設定)


(スクリプト)

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

public class PlayerController : MonoBehaviour
{
    public CharacterController controller;
    public float speed;
    private Vector3 moveDirection = Vector3.zero;
    private float gravity = 9.8f;

    void Update()
    {
        moveDirection.z = Input.GetAxis("Vertical");

        transform.Rotate(0, Input.GetAxis("Horizontal") * 6, 0);

        if(moveDirection.magnitude > 0.1f)
        {
            Vector3 globalDirection = transform.TransformDirection(moveDirection);
            controller.Move(globalDirection * speed * Time.deltaTime);
        }

        moveDirection.y -= gravity * Time.deltaTime;

        if(controller.isGrounded)
        {
            moveDirection.y = 0;
        }
    }
}