Unity の三人称カメラ

三人称カメラ は、プレイヤーの後ろに配置されるカメラの一種で、通常は少し横にずれて、ゲーム レベルとプレイヤー自体を視覚的に表現します。

Unity でサードパーソン シューティング (TPS) カメラを作成するには、通常のプレイヤーの動きとサードパーソン ビューを組み合わせて使用​​します。

Sharp Coder ビデオプレーヤー

ステップ 1: プレーヤー コントローラーを作成する

まず、回転と移動を処理するプレーヤー コントローラーを作成します。

  • 新しいゲーム オブジェクトを作成し (ゲーム オブジェクト -> 空の作成)、名前を付けます。 "Player"
  • 新しいカプセルを作成し (ゲーム オブジェクト -> 3D オブジェクト -> カプセル)、"Player" オブジェクト内に移動します。
  • Capsule Collider コンポーネントを Capsule から削除し、その位置を (0, 1, 0) に変更します。
  • 新しいゲームオブジェクトを作成して "CameraParent" という名前を付け、"Player" オブジェクト内に移動し、位置を (0, 1.64, 0) に変更します。
  • メイン カメラを "CameraParent" オブジェクト内に移動し、プレーヤーの後ろに移動します (私の場合は、この位置に移動しました: (0.5、0.6、-2.9))

Unity の三人称カメラ

  • という新しいスクリプトを作成し、SC_TPSController という名前を付け、その中に以下のコードを貼り付けます。

SC_TPSコントローラー.cs

using UnityEngine;

[RequireComponent(typeof(CharacterController))]

public class SC_TPSController : MonoBehaviour
{
    public float speed = 7.5f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Transform playerCameraParent;
    public float lookSpeed = 2.0f;
    public float lookXLimit = 60.0f;

    CharacterController characterController;
    Vector3 moveDirection = Vector3.zero;
    Vector2 rotation = Vector2.zero;

    [HideInInspector]
    public bool canMove = true;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
        rotation.y = transform.eulerAngles.y;
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            // We are grounded, so recalculate move direction based on axes
            Vector3 forward = transform.TransformDirection(Vector3.forward);
            Vector3 right = transform.TransformDirection(Vector3.right);
            float curSpeedX = canMove ? speed * Input.GetAxis("Vertical") : 0;
            float curSpeedY = canMove ? speed * Input.GetAxis("Horizontal") : 0;
            moveDirection = (forward * curSpeedX) + (right * curSpeedY);

            if (Input.GetButton("Jump") && canMove)
            {
                moveDirection.y = jumpSpeed;
            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        // Player and Camera rotation
        if (canMove)
        {
            rotation.y += Input.GetAxis("Mouse X") * lookSpeed;
            rotation.x += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotation.x = Mathf.Clamp(rotation.x, -lookXLimit, lookXLimit);
            playerCameraParent.localRotation = Quaternion.Euler(rotation.x, 0, 0);
            transform.eulerAngles = new Vector2(0, rotation.y);
        }
    }
}
  • の SC_TPSController スクリプトを "Player" オブジェクトにアタッチします (キャラクター コントローラーと呼ばれる別のコンポーネントも追加されていることがわかります。その中心値を (0, 1, 0) に変更します)。
  • "CameraParent" オブジェクトを "Player Camera Parent" 変数に代入します

ステップ 2: カメラ衝突検出を追加する

Camera 衝突検出は、カメラとプレーヤーの間に何かがあるかどうかをチェックするスクリプトで構成され、カメラを自動的に近づけて、カメラがオブジェクトをクリッピングするのを防ぎます。

  • 新しいスクリプトを作成し、SC_CameraCollision という名前を付けて、その中に以下のコードを貼り付けます。

SC_CameraCollision.cs

using UnityEngine;

public class SC_CameraCollision : MonoBehaviour
{
    public Transform referenceTransform;
    public float collisionOffset = 0.3f; //To prevent Camera from clipping through Objects
    public float cameraSpeed = 15f; //How fast the Camera should snap into position if there are no obstacles

    Vector3 defaultPos;
    Vector3 directionNormalized;
    Transform parentTransform;
    float defaultDistance;

    // Start is called before the first frame update
    void Start()
    {
        defaultPos = transform.localPosition;
        directionNormalized = defaultPos.normalized;
        parentTransform = transform.parent;
        defaultDistance = Vector3.Distance(defaultPos, Vector3.zero);

        //Lock cursor
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // LateUpdate is called after Update
    void LateUpdate()
    {
        Vector3 currentPos = defaultPos;
        RaycastHit hit;
        Vector3 dirTmp = parentTransform.TransformPoint(defaultPos) - referenceTransform.position;
        if (Physics.SphereCast(referenceTransform.position, collisionOffset, dirTmp, out hit, defaultDistance))
        {
            currentPos = (directionNormalized * (hit.distance - collisionOffset));

            transform.localPosition = currentPos;
        }
        else
        {
            transform.localPosition = Vector3.Lerp(transform.localPosition, currentPos, Time.deltaTime * cameraSpeed);
        }
    }
}
  • SC_CameraCollision スクリプトをメイン カメラにアタッチします。
  • "CameraParent" オブジェクトを "Reference Transform" 変数に代入します
  • カメラが壁を切り抜いている場合に備えて、"Collision Offset" と "Camera Speed" の値を微調整します。

TPS カメラの準備ができました。[再生] を押してテストします。

ソース
📁TPSCamera.unitypackage172.07 KB
おすすめの記事
Unity でパルクール システムを実装する
Unity用ヘリコプターコントローラー
Unity の 2D プラットフォーマー キャラクター コントローラーにダブル ジャンプ サポートを追加する
Unityでクレーンコントロールを作る方法
Unity用カーコントローラー
キャラクター コントローラー Unity でリジッドボディをプッシュする機能を追加する方法
Unity用飛行機コントローラー