0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Unity2D向けカメラスクリプト

0
Posted at

コピペして使います。プレーヤーにこのスクリプト、カメラ、リジッドボディ、アニメーターをそれぞれ用意してアタッチしてください。

using UnityEngine;

public class fps : MonoBehaviour
{
    [Header("Move/Jump")]
    public float moveSpeed = 10f;
    public float jumpForce = 5f;
    public float rotationDamping = 0.95f;

    [Header("Camera Follow (MainCamera 1本)")]
    public Camera mainCamera;                         // 未設定なら Camera.main
    public Vector3 followOffset = new Vector3(0f, 2f, -5f); // プレイヤーからの相対位置
    public float followSmooth = 12f;

    [Header("Animation")]
    public Animator animator;

    private Rigidbody rb;
    private Transform camTf;

    void Start()
    {
        rb = GetComponent<Rigidbody>();

        // Z方向を固定して左右移動のみ
        rb.constraints = RigidbodyConstraints.FreezeRotation |
                         RigidbodyConstraints.FreezePositionZ;

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;

        if (mainCamera == null) mainCamera = Camera.main;
        camTf = mainCamera.transform;

        if (animator == null) animator = GetComponent<Animator>();
    }

    void FixedUpdate()
    {
        MovePlayerLROnly();
        DampenRotation();
    }

    void Update()
    {
        Jump();
    }

    void LateUpdate()
    {
        FollowCamera();
    }

    void MovePlayerLROnly()
    {
        // 左右キーを逆にするために -1 を掛ける
        float h = -Input.GetAxis("Horizontal");

        Vector3 force = new Vector3(h * moveSpeed, 0f, 0f);
        rb.AddForce(force, ForceMode.Acceleration);

        if (animator)
            animator.SetBool("isWalking", Mathf.Abs(h) > 0.0001f);
    }

    void Jump()
    {
        if (Input.GetButtonDown("Jump"))
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            if (animator) animator.SetBool("isJump", true);
        }
        else
        {
            if (animator) animator.SetBool("isJump", false);
        }
    }

    void FollowCamera()
    {
        // プレイヤー位置に相対オフセットを足して追従
        Vector3 targetPos = transform.position + followOffset;
        camTf.position = Vector3.Lerp(camTf.position, targetPos,
            1f - Mathf.Exp(-followSmooth * Time.deltaTime));
    }

    void DampenRotation()
    {
        Vector3 av = rb.angularVelocity;
        av.x *= rotationDamping;
        av.y *= rotationDamping;
        av.z *= rotationDamping;
        rb.angularVelocity = av;
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?