🕹️ 실습 (CombatSystsemGame)
카메라
public class CameraController : MonoBehaviour
{
[SerializeField] Transform followTarget;
[SerializeField] float rotationSpeed = 2f;
[SerializeField] float distance = 5;
[SerializeField] float minVerticalAngle = -45;
[SerializeField] float maxVerticalAngle = 45;
[SerializeField] Vector2 framingOffset;
float rotationX;
float rotationY;
private void Start()
{
Cursor.visible = false;
}
private void Update()
{
//rotationX += Input.GetAxis("Mouse Y") * rotationSpeed;
rotationX -= Input.GetAxis("Mouse Y") * rotationSpeed;
rotationX = Mathf.Clamp(rotationX, minVerticalAngle, maxVerticalAngle);
rotationY += Input.GetAxis("Mouse X") * rotationSpeed;
var targetRotation = Quaternion.Euler(rotationX, rotationY, 0);
var focusPosition = followTarget.position + new Vector3(framingOffset.x, framingOffset.y, 0);
transform.position = focusPosition - targetRotation * new Vector3(0, 0, distance);
transform.rotation = targetRotation;
}
public Quaternion PlannerRotation => Quaternion.Euler(0, rotationY, 0);
}
플레이어
public class PlayerController : MonoBehaviour
{
CameraController cameraController;
[SerializeField] float moveSpeed = 5f;
[SerializeField] float rotationSpeed = 500f;
[SerializeField] float groundCheckRadius = 0.2f;
[SerializeField] Vector3 groundCheckOffset;
[SerializeField] LayerMask groundLayer;
Quaternion targetRotation;
Animator anim;
string moveAmountStr = "moveAmount";
CharacterController characterController;
bool isGrounded;
float ySpeed;
private void Awake()
{
cameraController = Camera.main.GetComponent<CameraController>();
anim = GetComponent<Animator>();
characterController = GetComponent<CharacterController>();
}
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
float moveAmount = Mathf.Clamp01(Mathf.Abs(h) + Mathf.Abs(v));
var moveInput = (new Vector3(h, 0, v)).normalized;
var moveDir = cameraController.PlannerRotation * moveInput;
GroundCheck();
if (isGrounded)
{
ySpeed = -0.5f;
}
else
{
ySpeed += Physics.gravity.y * Time.deltaTime;
}
var velocity = moveDir * moveSpeed;
velocity.y = ySpeed;
if (moveAmount > 0)
{
characterController.Move(velocity * Time.deltaTime);
transform.position += moveDir * moveSpeed * Time.deltaTime;
targetRotation = Quaternion.LookRotation(moveDir);
}
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
anim.SetFloat(moveAmountStr, moveAmount, 0.2f, Time.deltaTime);
}
void GroundCheck()
{
isGrounded = Physics.CheckSphere(transform.TransformPoint(groundCheckOffset), groundCheckRadius, groundLayer);
Debug.Log($"isGrounded = {isGrounded}");
}
private void OnDrawGizmos()
{
Gizmos.color = new Color(0, 1, 0, 0.5f);
Gizmos.DrawSphere(transform.TransformPoint(groundCheckOffset), groundCheckRadius);
}
}