using UnityEngine;
public class fps : MonoBehaviour
{
public float moveSpeed = 10f;
public float lookSpeed = 2f;
public float jumpForce = 5f;
public float rotationDamping = 0.95f;
public Transform playerCamera;
public Camera firstPersonCamera;
public Camera thirdPersonCamera;
public Animator animator;
private Rigidbody rb;
private float xRotation = 0f;
private bool isFirstPerson = true;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
// 初期状態で一人称視点カメラを有効にする
firstPersonCamera.enabled = true;
thirdPersonCamera.enabled = false;
animator = GetComponent<Animator>();
}
void FixedUpdate()
{
MovePlayer();
DampenRotation();
}
void Update()
{
LookAround();
Jump();
SwitchCamera();
}
void MovePlayer()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = transform.right * moveHorizontal + transform.forward * moveVertical;
Vector3 force = movement * moveSpeed;
rb.AddForce(new Vector3(force.x, 0, force.z));
if (movement != Vector3.zero) {
animator.SetBool("isWalking", true);
Debug.Log("running");
}
else{
Debug.Log("stop");
animator.SetBool("isWalking", false);
}
}
void LookAround()
{
float mouseX = Input.GetAxis("Mouse X") * lookSpeed;
float mouseY = Input.GetAxis("Mouse Y") * lookSpeed;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
playerCamera.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
transform.Rotate(Vector3.up * mouseX);
}
void DampenRotation()
{
Vector3 angularVelocity = rb.angularVelocity;
angularVelocity.x *= rotationDamping;
angularVelocity.z *= rotationDamping;
rb.angularVelocity = angularVelocity;
}
void Jump()
{
if (Input.GetButtonDown("Jump"))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
animator.SetBool("isJump", true);
}
else
{
animator.SetBool("isJump", false);
}
}
void SwitchCamera()
{
// カメラを切り替える
if (Input.GetKeyDown(KeyCode.C))
{
isFirstPerson = !isFirstPerson;
firstPersonCamera.enabled = isFirstPerson;
thirdPersonCamera.enabled = !isFirstPerson;
// プレイヤーのカメラを設定する
playerCamera = isFirstPerson ? firstPersonCamera.transform : thirdPersonCamera.transform;
}
}
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme