본문 바로가기

Unity/스크립트 Library

플레이어 대쉬, 회피 Dash, Dodge

 

Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    public float speed = 5;
    public float dashSpeed = 20;
    public float addSpeed;
    Vector3 finalDir;
    // Update is called once per frame
    void Update()
    {
        // 추가속력이 없다면(대쉬중이 아니라면)
        if (addSpeed == 0)
        {
            // 입력받은 축을 이용해서 방향을 만들고싶다.
            float h = Input.GetAxis("Horizontal");

            Vector3 dir = Vector3.right * h;
            // 현재방향을 기억하고싶다.
            finalDir = dir;

            // 대쉬중이 아닐때만 대쉬를 할 수있게 하고싶다.
            if (Input.GetKeyDown(KeyCode.LeftShift))
            {
                addSpeed = dashSpeed;
            }
        }

        // 최종속력은 기본속력 + 대쉬속력
        float finalSpeed = speed + addSpeed;
       
        rb.MovePosition(transform.position + finalDir * finalSpeed * Time.deltaTime);

        // 대쉬를 감속시키고싶다. 1초동안 감속하고싶다.
        if (addSpeed > 0)
        {
            addSpeed -= dashSpeed * Time.deltaTime;
        }
        else
        {
            addSpeed = 0;
        }

    }