プレーヤーキャラクターを動かす
公式情報
<2点間の特定の位置や回転方向を返す関数>
ゲーム開始時にキャラクタを必ず設地させておく
空中に配置した敵やプレーヤーを接地させるにはゲーム開始前にあらかじめキャラクターコントローラーの重力なし移動で
y軸にしかるべきマイナス値を入れて動かすと良い。地面のコリジョンに当たればそこで停まる
controller.Move (new Vector3 (0, -20, 0));
キャラクターコントローラーのMove関数を使って動かす例
下記メモの2.のパターン
using UnityEngine;
using System.Collections;
public class SimpleMoveControl : MonoBehaviour {
public float speed = 6.0F; public float jumpSpeed = 8.0F; public float rotateSpeed=10f; public float gravity = 20.0F; private Vector3 moveDirection = Vector3.zero; private CharacterController controller; // Use this for initialization void Start () { controller = GetComponent<CharacterController>(); } // Update is called once per frame void Update () { CameraAxisControl(); jumpControl(); attachMove(); attachRotation(); } //標準的なコントロール void NormalControl(){ if (controller.isGrounded) { moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); moveDirection = transform.TransformDirection(moveDirection); //?必要ない気もする moveDirection *= speed; } }
//カメラ軸に沿った移動コントロール void CameraAxisControl(){ if (controller.isGrounded) { Vector3 forward = Camera.mainCamera.transform.TransformDirection(Vector3.forward); Vector3 right = Camera.mainCamera.transform.TransformDirection(Vector3.right); moveDirection = Input.GetAxis("Horizontal")*right + Input.GetAxis("Vertical")*forward; moveDirection *= speed; } } //標準的なジャンプコントロール void jumpControl (){ if (Input.GetButton("Jump")) moveDirection.y = jumpSpeed; }
//移動処理 void attachMove (){ moveDirection.y -= gravity * Time.deltaTime; controller.Move(moveDirection * Time.deltaTime); } //キャラクターを進行方向へ向ける処理 void attachRotation(){ var moveDirectionYzero = -moveDirection; moveDirectionYzero.y=0; //ベクトルの2乗の長さを返しそれが0.001以上なら方向を変える(0に近い数字なら方向を変えない) if (moveDirectionYzero.sqrMagnitude > 0.001){ //2点の角度をなだらかに繋げながら回転していく処理(stepがその変化するスピード) float step = rotateSpeed*Time.deltaTime; Vector3 newDir = Vector3.RotateTowards(transform.forward,moveDirectionYzero,step,0f); transform.rotation = Quaternion.LookRotation(newDir); } }
}
非常にシンプルな例
下記メモの1.のパターン
using UnityEngine;
using System.Collections;
public class SimpleMoveScript : MonoBehaviour {
public float speed=0.5f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { transform.Translate(Input.GetAxis("Horizontal")*speed,0,Input.GetAxis("Vertical")*speed); }
}
メモ
■ユニティにおいて物体を動かすには3種類の方法がある
- オブジェクトのトランスフォーム情報(座標)を直接書き換える
- オブジェクトに剛体をアタッチして、物理的に力を加える
- キャラクタコントローラをアタッチして、移動機能を呼び出して動かす
tranlateは相対移動
positionは絶対指定
■CHARACTERCONTROLLERについて
- カプセルコライダーと移動機能をセットにしたコンポーネント
- スロープの処理、段差の処理、コライダーと衝突したときの押し出しの処理、移動量に対する遊びの処理、接地や運動量の検出など便利な機能が揃っている
- 後述のリジッドボディ特性はない(物理マテリアルによる反射などの現象は起きない)
- 他のリジッドボディ反応させるには、カスタムスクリプトが必要
メモに書いてある3.のパターン
void Start() {
// 右方向に力をかけて球を動かす rigidbody.AddForce(100, 0, 0);
}
メニュー
- 最終更新:2014-06-13 12:08:40