Unity 의 Main Camera 에 아래 Script 를 넣으면 카메라가 Scene 내부를 키보드와 마우스 움직임에 따라서
Camera 가 움직입니다.
좌우, 상하 움직임이 모두 되어서 마치 날라다니는 느낌을 줄 수 있습니다.
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class FlyCamera : MonoBehaviour
{
public float initialSpeed = 10f;
public float increaseSpeed = 1.25f;
public bool allowMovement = true;
public bool allowRotation = true;
public KeyCode forwardButton = KeyCode.W;
public KeyCode backwardButton = KeyCode.S;
public KeyCode rightButton = KeyCode.D;
public KeyCode leftButton = KeyCode.A;
public float cursorSensitivity = 0.025f;
public bool cursorToggleAllowed = true;
public KeyCode cursorToggleButton = KeyCode.Escape;
private float currentSpeed = 0f;
private bool moving = false;
private bool togglePressed = false;
private void OnEnable()
{
if (cursorToggleAllowed)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
private void Update()
{
if (allowMovement)
{
bool lastMoving = moving;
Vector3 deltaPosition = Vector3.zero;
if (moving)
currentSpeed += increaseSpeed * Time.deltaTime;
moving = false;
CheckMove(forwardButton, ref deltaPosition, transform.forward);
CheckMove(backwardButton, ref deltaPosition, -transform.forward);
CheckMove(rightButton, ref deltaPosition, transform.right);
CheckMove(leftButton, ref deltaPosition, -transform.right);
if (moving)
{
if (moving != lastMoving)
currentSpeed = initialSpeed;
transform.position += deltaPosition * currentSpeed * Time.deltaTime;
}
else currentSpeed = 0f;
}
if (allowRotation)
{
Vector3 eulerAngles = transform.eulerAngles;
eulerAngles.x += -Input.GetAxis("Mouse Y") * 359f * cursorSensitivity;
eulerAngles.y += Input.GetAxis("Mouse X") * 359f * cursorSensitivity;
transform.eulerAngles = eulerAngles;
}
if (cursorToggleAllowed)
{
if (Input.GetKey(cursorToggleButton))
{
if (!togglePressed)
{
togglePressed = true;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = !Cursor.visible;
}
}
else togglePressed = false;
}
else
{
togglePressed = false;
Cursor.visible = false;
}
}
private void CheckMove(KeyCode keyCode, ref Vector3 deltaPosition, Vector3 directionVector)
{
if (Input.GetKey(keyCode))
{
moving = true;
deltaPosition += directionVector;
}
}
}
Unity Visual Scripting 에서 Saved Variable Reset 하기 (0) | 2024.11.13 |
---|---|
Unity Image 파일을 sprite 로 변환하여 표시하기 (0) | 2024.05.07 |
Unity 자격증 인증서 받기 (0) | 2024.05.01 |
Unity 자격증 Badge 수령하기 - Credly (0) | 2024.04.30 |
Unity 자격증 취득! - Unity Certified Associate: Game Developer (0) | 2024.04.29 |