이번엔 Starter Asset에 들어있는 ThirdPersonController의 JumpAndGravity 함수를 살펴보고자 한다. Rigidbody가 없기때문에 중력과 점프를 직접 만든것이다.
private void JumpAndGravity()
{
if (Grounded)
{
// reset the fall timeout timer
_fallTimeoutDelta = FallTimeout;
// update animator if using character
if (_hasAnimator)
{
_animator.SetBool(_animIDJump, false);
_animator.SetBool(_animIDFreeFall, false);
}
// stop our velocity dropping infinitely when grounded
if (_verticalVelocity < 0.0f)
{
_verticalVelocity = -2f;
}
// Jump
if (_input.jump && _jumpTimeoutDelta <= 0.0f)
{
// the square root of H * -2 * G = how much velocity needed to reach desired height
_verticalVelocity = Mathf.Sqrt(JumpHeight * -2f * Gravity);
// update animator if using character
if (_hasAnimator)
{
_animator.SetBool(_animIDJump, true);
}
}
// jump timeout
if (_jumpTimeoutDelta >= 0.0f)
{
_jumpTimeoutDelta -= Time.deltaTime;
}
}
else
{
// reset the jump timeout timer
_jumpTimeoutDelta = JumpTimeout;
// fall timeout
if (_fallTimeoutDelta >= 0.0f)
{
_fallTimeoutDelta -= Time.deltaTime;
}
else
{
// update animator if using character
if (_hasAnimator)
{
_animator.SetBool(_animIDFreeFall, true);
}
}
// if we are not grounded, do not jump
_input.jump = false;
}
// apply gravity over time if under terminal (multiply by delta time twice to linearly speed up over time)
if (_verticalVelocity < _terminalVelocity)
{
_verticalVelocity += Gravity * Time.deltaTime;
}
}
Ground 조건문으로 땅에 붙어있는지, 떨어져있는지를 판단한다. 이는 Update에서 GroundCheck라는 함수를 통해 확인한다. GroundCheck는 Physics.CheckSphere를 통해 확인한다.
Grounded = Physics.CheckSphere(spherePosition, GroundedRadius, GroundLayers,
QueryTriggerInteraction.Ignore);
땅에 붙어있을 때. 즉, 공중상태가 아닐때에는 verticalVelocity에 -2를 할당하는것으로 무한히 값이 떨어지지 않게 한다.
// stop our velocity dropping infinitely when grounded
if (_verticalVelocity < 0.0f)
{
_verticalVelocity = -2f;
}
점프키를 누를때에는 공식을 이용한다. 해당 공식은 Mathf.Sqrt(Height * 02 * Gravity)로 이를통해 점프위치까지 도달하는데 필요한 velocity값을 구할 수 있다.
_verticalVelocity = Mathf.Sqrt(JumpHeight * -2f * Gravity);
떨어질때에 가속도를 주기위해 중력을 점점 더해준다.
// apply gravity over time if under terminal (multiply by delta time twice to linearly speed up over time)
if (_verticalVelocity < _terminalVelocity)
{
_verticalVelocity += Gravity * Time.deltaTime;
}
이를통해 rigidbody없이 점프와 중력을 만들어낸다.
'Unity' 카테고리의 다른 글
| 슬라임 타워 디펜스 (1) | 2024.11.22 |
|---|---|
| 애니메이션 특정부위에 이벤트 추가하기 (1) | 2024.11.13 |
| CharacterController (1) | 2024.11.07 |
| 적응형 UI (0) | 2024.11.06 |
| NewInputSystem (2) | 2024.11.05 |