Unity 오브젝트 이동방법

현동·2023년 9월 21일

Unity

목록 보기
2/6

Transform 컴포넌트:

Translate

게임 오브젝트를 이동시키기 위해 사용한다.

transform.Translate(Vector3.forward * speed * Time.deltaTime);  // 오브젝트를 전방으로 이동

Position

게임 오브젝트의 위치를 직접 변경

transform.position = new Vector3(10, 0, 0);  // 오브젝트의 위치를 (10, 0, 0)으로 설정

LookAt:

LookAt 메서드를 사용하면 오브젝트가 특정 지점을 바라보게 만들 수 있다. 오브젝트의 방향을 변경하며 움직이는 효과를 얻기 위해 자주 사용된다.

public Transform target;

void Update()
{
    transform.LookAt(target.position);
}

Vector

MoveTowards (등속이동)

현재 벡터를 대상 벡터로 지정된 속도로 이동시킨다. 지정된 최대 거리 이동만큼 벡터를 이동시키며, 대상 벡터에 도달하면 이동을 멈춤.

Vector3.MoveTowards(current, target, maxDistanceDelta);
// current는 현재 벡터, target은 목표 벡터
// maxDistanceDelta는 한 프레임에 이동할 수 있는 최대 거리를 의미

SmoothDamp (부드러운 감속 이동)

현재 벡터를 대상 벡터로 부드럽게 이동시키면서, 그 속도를 점점 줄여나가게 한다. 이 함수는 "댐핑"이라는 개념을 사용하여 원하는 값에 도달했을 때 급격한 변화를 방지.

Vector3.SmoothDamp(current, target, ref velocity, smoothTime);
// velocity는 참조로 전달되는 현재 속도 벡터 (밖에서 정의되어야 함)이며,
// smoothTime은 대상 값에 도달하는 데 걸리는 대략적인 시간을 초 단위로 나타낸다.

Lerp (선형 보간)

두 위치 사이를 부드럽게 이동하려면 Vector3.Lerp를 사용할 수 있다. 이를 통해 오브젝트를 부드럽게 한 위치에서 다른 위치로 이동시킬 수 있다.

public Transform target;
public float speed = 0.125f;

void Update()
{
    transform.position = Vector3.Lerp(transform.position, target.position, speed * Time.deltaTime);
}

Rigidbody 컴포넌트:

오브젝트에 물리 효과(중력, 충돌 등)를 적용하고 싶을 때 사용
Rigidbody (3D) 또는 Rigidbody2D (2D) 컴포넌트가 필요

Velocity

Rigidbody의 속도를 직접 조정하여 이동.

Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void Update()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
    rb.velocity = movement * speed;
}

AddForce

Rigidbody에 힘을 추가하여 이동시킨다.

  • Force: 연속적인 힘을 가한다.
rb.AddForce(movement * speed);
  • Impulse: 순간적인 힘 (임펄스)을 가한다.
rb.AddForce(movement * speed, ForceMode.Impulse);
  • Acceleration: 연속적인 가속도를 가한다.
  • VelocityChange: 현재 속도를 바로 변경할때 사용한다.

MovePosition

이는 Rigidbody의 위치를 직접 조정하되, 물리 시뮬레이션은 유지되는 방식으로 이동한다. 주로 충돌 검출이 필요한 경우에 사용.

Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
    Vector3 newPosition = rb.position + movement * speed * Time.fixedDeltaTime;
    rb.MovePosition(newPosition);
}

AddTorque

오브젝트에 회전 토크를 추가하여 회전시킨다.

Vector3 torque = new Vector3(1, 0, 0);
rb.AddTorque(torque);

AngularVelocity

Rigidbody의 회전 속도를 직접 설정하여 회전한다.

rb.angularVelocity = new Vector3(1, 0, 0);

마치며..

Rigidbody와 관련된 함수와 속성을 사용할 때는 주로 FixedUpdate 메서드를 사용하는 것이 좋다. FixedUpdate는 물리 연산과 관련된 업데이트 사이클에서 호출되기 때문.

0개의 댓글