Unity

[Unity] 플레이어 이동 코드

권벡터 2023. 6. 22. 21:51

코드

// 사용한 변수 모음 
public float MoveSpeed = 4.0f;
public float SprintSpeed = 6.0f;
public float SpeedChangeRate = 10.0f;
private float _speed;

//1. 목표 속도 설정: 플레이어가 sprint key를 눌렀는가에 따라 이동 속도 결정 됨.
//2. 만약 입력값이 0 이면 이동 속도도 0으로 결정한다.
//3. 현재 플레이어의 속도를 측정한다. 
//4. 스피드 오프셋을 정의한다.
//5. 플레이어가 목표 속도로 도달하기 위해 가속,감속 시킨다.
//6. 플레이어의 이동 방향을 정의한다. 
//7. 플레이어를 이동시킨다. 

void move()
{
    float targetSpeed = _input.sprint ? Sprint :MoveSpeed;
    
    if(_input.move ==Vector2.zero) targetSpeed = 0.0f;
    
    float currentHorizontalSpeed = new Vector3(_controller.velocity.x,0.0f,_controller.velocity.z).magnitude; 
    float speedOffset -0.1f;
    float inputMagnitude = _input.anologMovement ? _input.move.megnitude : 1f;
    
    if (currentHorizontalSpeed < targetSpeed - speedOffset || currentHorizontalSpeed > targetSpeed + speedOffset)
     {
     	_speed = Mathf.Lerp(currentHorizontalSpeed, targetSpeed * inputMagnitude, time.deltaTime * SpeedChangeRate);
        _speed = Mathf.Round(_speed * 1000f) /1000f;
     }
     else
     {
     	_speed = targetSpeed;
     }
     
     Vector3 inputDirection = new Vector3(_input.move.x,0.0f, _input.move.y).normalized;
     
     if (_input.move != Vector2.zero)
     {
     	inputDirection = transform.right * _input.move.x + transform.forward * _input.move.y;
     }
     
     _controller.Move(inputDirection.normalized * (_speed * Time.deltaTime) + new Vector3(0.0f, _verticalVelocity, 0.0f )* Time.deltaTime;
}