character Controllerの移動/ジャンプ
Step1「下準備」
1.まず移動したいオブジェクトを選択
2.「Add Component」から「CharacterController」を選択・追加
3.そのオブジェクトに新しい C#スクリプトを作成・アタッチ
※この際名前はなんでもいいです
Step2「コード記述」
次にキャラクターを動かすスクリプトを記述していきます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour
{
public float speed = 6.0F; //歩行速度
public float jumpSpeed = 8.0F; //ジャンプ力
public float gravity = 20.0F; //重力の大きさ
private CharacterController controller;
private Vector3 moveDirection = Vector3.zero;
private float h, v;
// Use this for initialization
void Start()
{
controller = GetComponent<CharacterController>();
}//Start()
// Update is called once per frame
void Update()
{
h = Input.GetAxis("Horizontal"); //左右矢印キーの値(-1.0~1.0)
v = Input.GetAxis("Vertical"); //上下矢印キーの値(-1.0~1.0)
if (controller.isGrounded)
{
moveDirection = new Vector3(h, 0, v);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}//Update()
}
動作確認して終了です。お疲れ様でした。
この記事が気に入ったらサポートをしてみませんか?