W298.dev
ProjectsPostsAbout Me
youtube
Pages
ProjectsPostsAbout Me
Posts
TAGS
All
RL-Obstacle-Avoid
RL-Competitive
Robot-Escape
Assembly Definition
ML-Agent
RL-Obstacle-Avoid
RL-Competitive
Unity
RL-Obstacle-Avoid
RL-Competitive
Robot-Escape
Assembly Definition
SERIES
RL-Obstacle-Avoid
RL-Competitive
Robot-Escape

Input Handle & Follow Cam

1. Player Input Handle

Input.GetKeyDown 이나 Input.GetAxis 를 이용한 Legecy 방법도 있지만, 이번엔 좀 다르게 하려고 한다.
Package Manager 에 있는 Input System 을 이용했다.
https://velog.velcdn.com/images/lutca1320/post/328e343c-8109-424f-b7ea-145ffa1a04b7/image.png
InputAction 을 Public 으로 선언하면 위처럼 Inspector 에 설정할 수 있게 뜬다.
  • movementAction - 플레이어 Movement (WASD)
  • aimAction - 조준 모드 (마우스 Right Button)
  • crouchAction - 앉기 (키보드 C 버튼: Toggle)
  • fireAction - 총기 발사 (마우스 Left Button)
1public class RobotInputHandler : MonoBehaviour
2{
3    public InputAction movementAction;
4    public InputAction fireAction;
5    public InputAction aimAction;
6    public InputAction crouchAction;
7
8	private Vector2 movementAxis;
9    public Vector2 movementVector = new(0, 0);
10    public bool isCrouch = false;
11    public bool isAim = false;
12    public bool isMoving = false;
13    public bool isFire = false;
14
15    void Start()
16    {
17        movementAction.Enable();
18        crouchAction.Enable();
19        aimAction.Enable();
20
21        crouchAction.performed += context =>
22        {
23            isCrouch = !isCrouch;
24        };
25    }
26
27    void FixedUpdate()
28    {
29        movementAxis = movementAction.ReadValue<Vector2>();
30
31        isAim = aimAction.ReadValue<float>() == 1;
32        isFire = fireAction.ReadVale<float>() == 1;
33        isMoving = movementAxis != Vector2.zero || movementVector.magnitude > 0.05f;
34
35        movementVector = isMoving ? Vector2.Lerp(movementVector, movementAxis, Time.deltaTime * 7f) : new(0, 0);
36        transform.position += new Vector3(movementVector.x, 0, movementVector.y) / (isCrouch || isAim ? 30 : 15);
37    }
38}
39
movementAxis 의 각 축의 값이 0 or 1이라서 움직임이 자연스럽지 않았다. Vector2.Lerp 를 통해 보간한 값인 movementVector 를 활용해 position 을 컨트롤했다.
Aim 이나 Crouch 하면 속도가 느려져야 하므로 isCrouch || isAim ? 30 : 15 로 설정했다. 나중에 속도 증가 아이템이나 감소 아이템 사용 시 바뀌어야 하므로 수정할 예정

2. FollowCam

https://velog.velcdn.com/images/lutca1320/post/803410f8-55e9-4520-8714-53de8af89548/image.png
Player 가 가지고 있는 컴포넌트이다.
  • Attached Cam - 부착할 카메라
  • Offset - 카메라와 플레이어 간의 Position Offset
1public class PlayerFollowCam : MonoBehaviour
2{
3    public Camera attachedCam;
4    public Vector3 offset;
5
6    void FixedUpdate()
7    {
8        attachedCam.transform.position = Vector3.Lerp(attachedCam.transform.position, transform.position + offset, Time.deltaTime * 2);
9    }
10}
11
이것도 Vector3.Lerp 를 통해 보간했다.