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