Game Development, 게임개발/개발

GameObject 움직이는 여러가지 방법 [Unity]

게임이 더 좋아 2021. 2. 24. 19:07
반응형
728x170

사실 translate()라는 메서드를 소개했지만 다른 방법도 많기에 조금 더 다뤄보려고 한다.

 

 

 

움직인다는 말은 여러가지의 의미가 있다.

 

이전 위치와 다른 위치를 갖게 된다면 그것을 움직인다는 말로 우리는 이해하겠다.

 

즉, 순간이동을 하든, 뛰어가든, 날라가든, 위치의 변화가 생겼으면 바로 그것이 움직인 것이라 보겠다.

 


 

기본 전제

 

3D 환경

Sphere (3D)

Empty Object (Name: Target)

C# script (whatever)

 

1. Set position

 

public class NewBehaviourScript : MonoBehaviour
{
    public Transform target;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        transform.position = target.position;
    }
}

Play를 누르면 공이 바로 Target으로 향한다.

이건 뭐 움짤로 보여줄 필요도 없다.

 

++ 물론 Script는 Sphere에다 넣어주어야 한다. 또한 Transform도 Target으로 직접 넣어주자.

 

-> 느낌 그냥 고정되었다? 마우스가 Target을 움직이는 대로 고정되어있음

음.. 마우스에 따라 옮길 수 있겠는걸? 만약 Onclick 기능을 이용하면 내가 집었다는 느낌을 줄 수 있겠는 걸?

하면 굿


 

2. Lerp

 

좌표 2개를 이용한다.

약간 자석의 느낌을 줄 수 있다.

public class NewBehaviourScript : MonoBehaviour
{
    public Transform target;
    public float speed = 0.1f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 a = transform.position;
        Vector3 b = target.position;
        transform.position = Vector3.Lerp(a, b, speed);
    }
}

 

 

음 그렇구나

t가 커지면 어떨까??? -> 걍 SetPosition이랑 다를 바 없음

 

 

3. Move Toward

 

거의 똑같다. 하지만 얘는 Smooth하지 못해.. 프레임마다 일정한 속도가 있다.

그냥 가까우나 머나 같은 속도로 따라온다.

 

위의 코드에서 Lerp만 MoveTowards로 바꿔주자

 

음.. ? 어디다 쓰일까??

엘리베이터나 써야지

 

 

 

 

** Move Toward와 Lerp를 섞어서 가능하다.

아래와 같이 바꿔주자.

t는 임의로 정해주자 나는 0.1f로 했다.

        transform.position = Vector3.MoveTowards(a, Vector3.Lerp(a,b,t), speed);

 

 

 

4. Rigidbody

 

대망의 Rigidbody

내가 생각하기에 제일 자연스러울 것 같은 방법! 가속도가 있어서 그럼 

** F=ma 

Sphere에다 rb를 추가해주시구요

 

 

-AddForce

public class NewBehaviourScript : MonoBehaviour
{
    public Transform target;
    public Rigidbody rb;
    public float speed = 0.1f;
    public float t = 0.1f;
    public float force;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 f = target.position - transform.position;
        f = f.normalized;
        f = f * force;
        rb.AddForce(f);
    }
}

**왜 postion - postion이 direction이 될까요?

기하와 벡터를 잘 배웠으면 뺀다는 것의 의미를 알 수 있다.

 

** 왜 normalized(정규화)를 해서 크기를 1로 만들까요?

-> 방향벡터라는 것을 알면 잘 이해가 된다.

 

** 수렴하지 않는다면 rb의 drag수치를 조정해주자 난 2로 했다.

-> Drag란 

How much air resistance affects the object when moving from forces. 0 means no air resistance, and infinity makes the object stop moving immediately.

공기저항을 뜻한다.

 

-MovePosition

약간 도착하면 부들부들 떨리는 편

public class NewBehaviourScript : MonoBehaviour
{
    public Transform target;
    public Rigidbody rb;
    public float force = 5.0f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 f = target.position - transform.position;
        f = f.normalized;
 
        rb.MovePosition(transform.position+(f * Time.deltaTime * force));
    }
}

 

 

 

 

-SetVelocity

public class NewBehaviourScript : MonoBehaviour
{
    public Transform target;
    public Rigidbody rb;
    public float force = 50.0f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 f = target.position - transform.position;
        f = f.normalized;
        rb.velocity = (f * force * Time.deltaTime);
    }
}

 

얘도 큰 무대에선 잘 떠는 편

 

 

 

끝 맘대로 다양하게 다른 방법도 많으니 알아서 찾아서 써보자

 


참고링크

www.youtube.com/watch?v=-thhMXmTM7Q

 

반응형
그리드형