Unity

[Unity] Player Movement Script

Guk-blog 2020. 3. 16. 16:17
728x90
반응형
public CharacterController controller;
    public float speed = 10f;
    public float gravity = -19.62f;
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    public float jumpHeight = 3f;

    Vector3 velocity;
    bool isGrounded;

    private void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);//땅에 붙어 있는지 확인

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -2f; // 자연스럽게 떨어지는 속도 조절 가능
        }

        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * y;

        controller.Move(move * speed *Time.deltaTime); // 플레이어 x,y축 움직임

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);//점프
        }
        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime); // 중력에 의한 움직임
    }

출처 : https://www.youtube.com/watch?v=_QajrabyTJc

728x90
반응형