[ ps ]
[ 백준 / C++ ] 2644 : 촌수계산 (tistory.com)
[ Unity ]
키 입력에 따라 행동이 실행되고, 이 과정에서 플레이어에 힘을 적용시켜야 하는 경우가 생겼다. ex) jump
원래는 rigidbody의 velocity를 가져와서 힘을 적용한 새로운 velocity를 적용시켜줬는데,
마찰, 중력 등의 물리계산을 더 정확히 적용시키기 위해 AddForce 메서드를 사용하는 방식으로 변경하였다.
protected void ForceMove(Vector2 direction, float force)
{
stateMachine.player.rigidBody.AddForce(direction.normalized * force, ForceMode2D.Impulse);
}
이 메서드를 통해 jump 액션을 쉽게 구현할 수 있었다.
반면 attack 액션을 할 때 공격 방향으로 힘을 적용시키고 싶었는데, ForceMove 메서드가 적용되지 않았다.
알고보니 Update 메서드에서 매 프레임마다 Move 메서드를 호출하여 x축 속도를 설정하고 있었기 때문에,
ForceMove 메서드에서 적용한 힘이 즉시 덮어써지고 있었다.
private void Move(Vector2 direction)
{
float movementSpeed = GetMovementSpeed();
// before velocity
Vector2 currentVelocity = stateMachine.player.rigidBody.velocity;
// after velocity
currentVelocity.x = direction.x * movementSpeed;
// update velocity
stateMachine.player.rigidBody.velocity = currentVelocity;
}
수정의 경우는 간단한 방법을 사용했다.
플레이어가 공격할 때에는 move 액션을 하지 않기에 공격 중에는 Move 메서드를 호출하지 않았다.
private void Move()
{
Vector2 movementDirection = GetMovementDirection();
if (!stateMachine.isAttacking) Move(movementDirection);
}
'TIL' 카테고리의 다른 글
[ 24.07.16 ] 내일배움캠프 TIL - Ray, LineRenderer (0) | 2024.07.16 |
---|---|
[ 24.07.10 ] 내일배움캠프 TIL - Attack Trigger2 (0) | 2024.07.10 |
[ 24.07.05 ] 내일배움캠프 TIL - 2D게임에서 Ground 판단하기 (0) | 2024.07.06 |
[ 24.06.27 ] 내일배움캠프 TIL - 기획, Trail Renderer? (0) | 2024.06.27 |
[ 24.06.24 ] 내일배움캠프 TIL - .gitignore (0) | 2024.06.24 |