今回は操作するプレイヤーを作っていきます。
目次
デバッグシーンの作成
まずプレイヤーのを動かす為のシーンを作成します。
プロジェクト作成時に作られていた「SampleScene」の名前を「DebugScene」に変更して開きます。
プレイヤーオブジェクトの作成
次にデバッグシーン上にプレイヤーオブジェクトと地面のオブジェクトを配置します。
今回はモデルがまだ出来ていないので、仮でcubeになっています。
移動スクリプトの作成
プレイヤーを移動させるスクリプトを作成します。
「PlayerConctorller」という名称で以下のスクリプトを作成しました。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 6.0F; //歩行速度
public float gravity = 20.0F; //重力の大きさ
public FloatingJoystick joystick;
private CharacterController m_Controller;
void Start()
{
m_Controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void FixedUpdate()
{
var h = joystick.Horizontal;
var v = joystick.Vertical;
Vector3 moveDirection = new Vector3(h, 0, v);
moveDirection *= speed;
moveDirection.y -= gravity;
// キャラクターを移動
m_Controller.Move(moveDirection * Time.deltaTime);
// キャラクターを進行方向に回転
Vector3 rotDirection = new Vector3(moveDirection.x, 0, moveDirection.z).normalized;
if (rotDirection.magnitude > 0.05f)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(rotDirection), 0.1f);
}
}
}
また、ジョイスティックには「Joystick Pack」を使用しました。
これでプレイヤーを動かせるようになりました。