게임을 만들며 플레이어의 이동을 구현하던 도중 플레이어가 떨어지지 않는 문제가 발생했다.
점프를 하도록 만들어봤는데 점프도 똑바로 되지 않는다.
1. 문제상황
이 문제의 원인은 플레이어의 이동을 Rigidbody.velocity로 만들어서 발생한다.
2. 원인
스크립트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Rigidbody rb;
public float speed = 8f;
public float jumpforce = 10f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float xSpeed = Input.GetAxis("Horizontal") * speed;
float zSpeed = Input.GetAxis("Vertical") * speed;
rb.velocity = new Vector3(xSpeed, 0f, zSpeed); // 문제가 생기는 부분
if(Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jumpforce, ForceMode.Impulse);
}
}
}
Rigidbody.velocity 는 Rigidbody의 속도를 직접 수정한다.
그래서 y속도를 고정해 뒀기 때문에 y방향 이동이 되지 않는 것이다.
3. 해결방법
유니티 문서를 확인해 보면 velocity를 직접 수정하지 말고 Addforce를 쓰는 것을 권장한다
In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour - use AddForce instead Do not set the velocity of an object every physics step, this will lead to unrealistic physics simulation.
유니티에서는 물리법칙을 자체적으로 구현해 뒀다.
Addforce를 사용하면 그 물리법칙을 이용해 오브젝트에 힘을 가하는 방식으로 작동한다.
하지만 velocity를 직접 수정하는 방식은 물리법칙을 무시하고 강제로 속도값을 변경한다.
그러니 이동을 velocity가 아닌 Addforce로 작성하면 조금 더 자연스러운 움직임을 구현할 수 있다.
하지만 velocity를 사용해서 속도를 바꾸면 Addforce보다 즉각적으로 속도가 변경된다는 장점이 있다.
그러니 velocity를 계속 쓰고 싶은 경우를 위해 y축 속도를 자연스럽게 바꾸는 방법도 적어보자면
rb.velocity = new Vector3(xSpeed,rb.velocity.y, zSpeed);
velocity의 y축 속도를 Rigidbody.velocity.y로 바꾸면 자연스러운 y축 움직임을 구현할 수 있다.
출처
https://docs.unity3d.com/2023.2/Documentation/ScriptReference/Rigidbody-velocity.html
'Unity' 카테고리의 다른 글
Delegate, Action, Event (1) | 2024.11.07 |
---|---|
벡터 (0) | 2024.11.01 |
Null 관련 연산자 (3) | 2024.10.31 |
비동기 프로그래밍 (0) | 2024.09.08 |