본문 바로가기

Project/우다다다 고영희

[우다다다 고영희] Unity: 자동차 오브젝트 움직이기

728x90

우다다다 고영희에서 사용되는 자동차 오브젝트를 IEnumerator를 통해서 움직이게 해보겠다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Car : MonoBehaviour
{
    public float moveSpeed;
    public Vector2 initTarget = new Vector2(200);
 
    Rigidbody2D rigid;
    Vector2 target;
 
    void Start()
    {
        rigid = GetComponent<Rigidbody2D>();
    }
 
    void OnEnable()
    {
        StartCoroutine(Move());    
    }
 
    void OnDisable()
    {
        transform.position = initTarget;
        StopCoroutine(Move());
    }

 

  • moveSpeed - 자동차의 움직이는 속도를 저장하는 변수이다.
  • initTarget - 초기 생성 위치를 저장하는 변수이다.

OnEnable을 통해서 오브젝트 풀에서 활성화 될때마다 코루틴을 시작해준다. OnDisable를 통해서 비활성화된 오브젝트를 초기 위치로 이동시켜주고, 코루틴을 중단시켜준다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 IEnumerator Move()
    {
        float y = transform.position.y + Random.Range(-34);
 
        while (true)
        {
            float x = transform.position.x - 1f;
 
            target = new Vector2(x, y);
 
            while (Vector2.Distance(transform.position, target) > 0.01f)
            {
                transform.position = Vector2.MoveTowards(transform.position, target, moveSpeed);
                yield return null;
            }
 
            yield return new WaitForSeconds(0.1f);
        }
    }
}
 

 

자동차는 생성되고 단 한번만 y값을 조정해준다. 그리고 target을 설정해주고 11행의 조건에 만족할때까지 MoveTowards를 사용하여 자동차를 움직이게 해준다.

728x90