【ダークソウル風ゲームを作りたい(Unity)。その2】
今回はマウスに合わせたカメラの動作を実装します。
youtu.be
・空オブジェクトCameraHolderを作成します。positionはプレイヤーポジションと同じにします。
また、CameraHolderの直下にCameraPivotを作成し、CameraPivotの直下にMainCameraを移動する。
・カメラ制御を行うスクリプトを作成します。
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SG { public class CameraHandler : MonoBehaviour //+EP2 cameraHolderにアタッチ { public Transform targetTransform; public Transform cameraTransform; public Transform cameraPivotTransform; private Transform myTransform; private Vector3 cameraTransformPosition; private LayerMask ignoreLayers; // public static CameraHandler singleton; //CameraHandlerクラスのシングルトン宣言 public float lookspeed = 0.1f; public float followspeed = 0.1f; public float pivotSpeed = 0.03f; private float defaultPosition; private float lookAngle; private float pivotAngle; public float minimumPivot = -35; public float maximumPivot = 35; // public float cameraSmoothTime = 0.2f; private Vector3 cameraFollowVelocity = Vector3.zero; //+EP3 private void Awake() { // singleton = this; myTransform = transform; defaultPosition = cameraTransform.localPosition.z; ignoreLayers = ~(1 << 8 | 1 << 9 | 1 << 10); } //カメラpositionを設定 public void FollowTarget(float delta) { //cameraHolderとプレイヤーの位置を徐々に近づける。 Vector3 targetPosition = Vector3.Lerp(myTransform.position, targetTransform.position, delta / followspeed); //Vector3 pos = Vector3.Lerp(a, b, t);t で a と b の間を補間.t=0のときpos=a,t=0.5のときpos=aとbの中間値、t=1のときpos=a //myTransform.position:カメラポジション targetTransform.position:プレイヤー位置 delta / followspeed:0.02/0.1=0.2 myTransform.position = targetPosition; } //カメラRotationを設定 public void HandCameraRotation(float delta,float mouseXInput,float mouseYInput) { lookAngle += (mouseXInput * lookspeed) / delta; // Debug.Log("lookAngle:" + lookAngle); pivotAngle -= (mouseYInput * pivotSpeed) / delta; // Debug.Log("pivotAngle:" + pivotAngle); //pivotAngleをminimum~maximumの範囲内の値で制限し、その値を返す pivotAngle = Mathf.Clamp(pivotAngle, minimumPivot, maximumPivot); //CameraHolderのRotationのy値を設定 Vector3 rotation = Vector3.zero; rotation.y = lookAngle; Quaternion targetRotation = Quaternion.Euler(rotation); //myTransform.rotation = targetRotation; //CameraPivotのRotationのx値を設定 rotation = Vector3.zero; rotation.x = pivotAngle; targetRotation = Quaternion.Euler(rotation); cameraPivotTransform.localRotation = targetRotation; } } }
public class InputHandler : MonoBehaviour //+EP1 playerにアタッチ { (省略) //+EP2 private void FixedUpdate() { //1フレームの時間幅:0.0167 float delta = Time.fixedDeltaTime; // Debug.Log("delta:" + delta); if (cameraHandler != null) { cameraHandler.FollowTarget(delta); cameraHandler.HandCameraRotation(delta, mouseX, mouseY); } } }
今回は以上です。