'유니티 객체 이동및 충돌'에 해당되는 글 1건

  1. 2019.12.02 12.02 객체 충돌

12.02 객체 충돌

C#/Study 2019. 12. 2. 23:44

예제: Hero 게임 오브젝트가 특정 지역으로 이동중일때 어떤 객체와 부딪히면 문자열을 출력한다.

코드:

 

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using UnityEngine;
public class App : MonoBehaviour
{
    public Button btnMoveCoroutine;
    public Button btnMoveUpdate;
    public Hero hero;
    public GameObject targetPoint;
    // Start is called before the first frame update
    void Start()
    {
        //GameObject heroGO = new GameObject("Hero");
        //hero = heroGO.AddComponent<Hero>();
 
        //string path = string.Format("Prefabs/{0}", "ch_01_01");
        //var prefab = Resources.Load<GameObject>(path);
        //var model = Instantiate(prefab);
        //model.transform.SetParent(heroGO.transform, false);
        //model.transform.localPosition = Vector3.zero;
        //hero.model = model;
 
        hero.onMove = (target) =>
        {
            var dis = Vector3.Distance(hero.transform.position, target.transform.position);
            var vc = target.transform.position - hero.transform.position;
            var dir = vc.normalized;
            var speed = 1;
            hero.transform.position += dir * speed * Time.deltaTime;
            if (dis <= 0.5f)
            {
                hero.transform.position = target.transform.position;
                hero.model.GetComponent<Animation>().Play("idle@loop");
                hero.isMove = false;
            }
        };
 
        btnMoveCoroutine.onClick.AddListener(() =>
        {
            hero.Move2(targetPoint);
        });
        btnMoveUpdate.onClick.AddListener(() => {
            hero.Move(targetPoint);
        });
 
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Hero : MonoBehaviour
{
    public bool isMove;
    public Action<GameObject> onMove;
    public GameObject target;
    public GameObject model;
    IEnumerator onMoveCoroutine;
    // Start is called before the first frame update
    void Start()
    {
        onMoveCoroutine = OnMoveCoroutine();
    }
 
    public void Move(GameObject target)
    {
        this.target = target;
        isMove = true;
    }
    public void Move2(GameObject target)
    {
 
        this.target = target;
        //isMove = true;
        this.model.GetComponent<Animation>().Play("run@loop");
        StartCoroutine(onMoveCoroutine);
    }
    public void Update()
    {
        if (this.isMove == true)
        {
            this.model.GetComponent<Animation>().Play("run@loop");
            this.onMove(target);
        }        
        if (this.transform.position == target?.transform.position)
        {
            StopCoroutine(onMoveCoroutine);
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag == "Player")
        {
            Debug.Log("부딫혔습니다.");
        }
    }
 
    IEnumerator OnMoveCoroutine()
    {
        while (true)
        {
            var dis = Vector3.Distance(this.transform.position, target.transform.position);
            var vc = target.transform.position - this.transform.position;
            var dir = vc.normalized;
            var speed = 1;
            this.transform.position += dir * speed * 0.01f;
            this.transform.LookAt(target.transform);
            if (dis <= 0.1f)
            {
                this.model.GetComponent<Animation>().Play("idle@loop");
                this.transform.position = target.transform.position;
                //isMove = false;
            }
            yield return new WaitForSeconds(0.01f);
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

코드뿐만 아니라 유니티에서 Hero 게임오브젝트와 collider 오브젝트에 각각 Box Collider, Rigid Body 컴포넌트를 부착하고 is Trigger와 is Kinematic 항목에 체크표시를 해주었다.

'C# > Study' 카테고리의 다른 글

12.10 오브젝트 풀 활용  (0) 2019.12.10
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
struct 와 클래스의 차이  (0) 2019.11.02
ref 와 out  (0) 2019.10.31
초기화  (0) 2019.10.31
: