728x90
1. MouseLookAt | 마우스를 이용한 부드러운 바라보기
2. Shake | 스페이스바를 이용하여 카메라 떨림 구현
3. 계속 추가예정
using System.Collections;
using UnityEngine;
public class CameraTest : MonoBehaviour
{
[SerializeField] Transform target;
[SerializeField] float mouseXSpeed = 10f;
[SerializeField] float mouseYSpeed = 10f;
//카메라 pivot값
[SerializeField] Vector3 cameraPivot = new Vector3(0.2f, 1.5f, -2f);
// 마우스 회전값
float xRotation = 0f;
float yRotation = 0f;
[Header("카메라 회전 제한값")]
[SerializeField] float minXRotation = -45f;
[SerializeField] float maxXRotation = 45f;
[SerializeField] float minYRotation = -30f;
[SerializeField] float maxYRotation = 45f;
[Header("카메라 회전 부드러움")]
[SerializeField] float smoothTime = 0.1f;
float xRotationVelocity = 0f;
float yRotationVelocity = 0f;
[Header("카메라 흔들림")]
[SerializeField] float shakeTime = 1f;
[SerializeField] float shakeMagnitude = 0.1f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
ResetCameraPosition();
ResetMouseRotation();
}
void Update()
{
ResetCameraPosition();
MouseLookAt();
if (Input.GetKeyDown(KeyCode.Space))
{
CameraShake();
}
}
private void ResetMouseRotation()
{
xRotation = 0f;
yRotation = 0f;
}
private void MouseLookAt()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * mouseXSpeed;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * mouseYSpeed;
xRotation -= mouseY;
yRotation += mouseX;
xRotation = Mathf.Clamp(xRotation, minXRotation, maxXRotation);
yRotation = Mathf.Clamp(yRotation, minYRotation, maxYRotation);
float smoothX = Mathf.SmoothDampAngle(transform.eulerAngles.x, xRotation, ref xRotationVelocity, smoothTime);
float smoothY = Mathf.SmoothDampAngle(transform.eulerAngles.y, yRotation, ref yRotationVelocity, smoothTime);
Vector3 dir = new Vector3(smoothX, smoothY, 0);
transform.rotation = Quaternion.Euler(dir);
}
private void CameraShake()
{
StopCoroutine("Shacke");
ResetCameraPosition();
StartCoroutine(Shake(shakeTime, shakeMagnitude));
}
private void ResetCameraPosition()
{
transform.position = target.position + cameraPivot;
}
IEnumerator Shake(float time, float magnitude)
{
float elapsedTime = 0f;
while (elapsedTime < time)
{
float x = Random.Range(-1f, 1f) * magnitude; // 좌우
float y = Random.Range(-1f, 1f) * magnitude; // 위아래
float z = Random.Range(-1f, 1f) * magnitude; // 앞뒤
Vector3 offset = Random.insideUnitCircle * magnitude; // x, y 값을 동시에 랜덤하게 설정
transform.position = target.position + cameraPivot + new Vector3(0, y, 0);
elapsedTime += Time.deltaTime;
yield return null;
}
ResetCameraPosition();
}
}
728x90
'unity > 유니티 초보' 카테고리의 다른 글
Unity - firebase realtimeDatabase, auth를 이용한 채팅 구현해보기 (0) | 2024.08.15 |
---|---|
Unity - prefab을 이용한 간단한 ObjectPool (0) | 2024.05.30 |
Unity - 부드러운 카메라 회전 (0) | 2024.05.27 |
Unity - Lerp 다양한 사용법 (0) | 2024.05.27 |
Unity - rootMotion 설정 창 열리지 않을때 <root contain root motion curve> (0) | 2024.04.24 |