'전체 글'에 해당되는 글 139건

  1. 2019.12.10 12.10 오브젝트 풀 활용
  2. 2019.12.09 12.09 드래곤플라이트 2 (이펙트 추가)
  3. 2019.12.09 12.09 충돌감지와 sprite활용하기(delegate)
  4. 2019.12.08 2019.12.08 드래곤플라이트 과제
  5. 2019.12.06 12.06 드래곤플라이트 구현
  6. 2019.12.05 12.05 유닛 바라보기 (LookAt 메서드 사용X) 1
  7. 2019.12.02 12.02 객체 충돌
  8. 2019.11.29 11.29 캐릭터 움직이기 (Coroutine, Update 비교 및 활용)

12.10 오브젝트 풀 활용

C#/Study 2019. 12. 10. 16:47

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App : MonoBehaviour
{
    public Button btn;
    public GameObject bulletPrefab;
    public objectPool objectPool;
    // Start is called before the first frame update
    void Start()
    {
        this.objectPool.Init(this.bulletPrefab);
        this.objectPool.PreLoad();
 
        btn.onClick.AddListener(() => {
            var bullet = this.objectPool.GetBullet();
            var initPos = new Vector3(001);
            bullet.Init(initPos);
            bullet.onDestroy = () =>
            {
                objectPool.Release(bullet);
            };
        });
 
    }
}
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Bullet : MonoBehaviour
{
    public float speed =3.5f;
    public System.Action onDestroy;
    private Coroutine coroutine;
    public void Init(Vector3 initPos)
    {
        this.transform.position = initPos;
        this.gameObject.SetActive(true);
        this.Move();
    }
    public void Move()
    {
        coroutine = this.StartCoroutine(this.MoveImpl());
    }
    public IEnumerator MoveImpl()
    {
        while(true)
        {
            this.transform.Translate(Vector3.up * this.speed * Time.deltaTime);            
            yield return null;
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.LogFormat("OnTriggerEnter2D:{0}", collision);
        StopCoroutine(coroutine);
        this.onDestroy();
    }
    
}
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class objectPool : MonoBehaviour
{
    private List<Bullet> bullets;
    private GameObject bulletPrefab;
    public void Init(GameObject bulletprefab)
    {
        this.bullets = new List<Bullet>();
        this.bulletPrefab = bulletprefab;
    }
    public void PreLoad()//만들기
    {
        for(int i =0; i<10; i++)
        {
            var bulletGo = Instantiate<GameObject>(this.bulletPrefab);
            bulletGo.transform.SetParent(this.transform, false);
            bulletGo.transform.localPosition = Vector3.zero;
            bulletGo.SetActive(false);
            var bullet = bulletGo.GetComponent<Bullet>();
            this.bullets.Add(bullet);
        }
    }
    public Bullet GetBullet() //꺼내기
    {
        Bullet bullet = null;
        if (this.bullets.Count > 0)
        {
            bullet = this.bullets[0];
            this.bullets.RemoveAt(0);
            bullet.gameObject.SetActive(true);
            bullet.transform.SetParent(null);
        }
        else
        {
            //재사용할 총알 없음
            bullet = Instantiate<GameObject>(this.bulletPrefab).GetComponent<Bullet>();           
        }
        return bullet;
    }
    public void Release(Bullet bullet) // 넣기
    {
        bullet.transform.SetParent(this.transform, false);
        bullet.transform.localPosition = Vector3.zero;
        bullet.gameObject.SetActive(false);
        this.bullets.Add(bullet);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

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

Sprite Atlas 사용하기  (0) 2019.12.18
오브젝트 풀링 (인스턴스로 접근)  (0) 2019.12.16
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
:

12.09 드래곤플라이트 2 (이펙트 추가)

C#/Study 2019. 12. 9. 22:15

 

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App : MonoBehaviour
{
    public Ship ship;
    public Button CreateEnemy;
    public Button CreateShip;
    private bool enemyExist = false;
    private GameObject enemyPrefab;
    public static GameObject bulletPrefab;
    public static GameObject explosion;
    private GameObject shipPrefab;
    // Start is called before the first frame update
    private void Awake()
    {
        bulletPrefab = Resources.Load<GameObject>("fireball-blue-med");
        enemyPrefab = Resources.Load<GameObject>("ship1");
        shipPrefab = Resources.Load<GameObject>("ship2");
        explosion = Resources.Load<GameObject>("Animations/Explosion");
    }
    void Start()
    {
        CreateShip.onClick.AddListener(() =>
        {
            if(GameObject.Find("Ship"== null)
            {
                GameObject shipGO = new GameObject("Ship");
                ship = shipGO.AddComponent<Ship>();
                var model = Instantiate(shipPrefab);
                ship.transform.position = new Vector3(0-1.237f, -1.7045f);
                model.transform.SetParent(shipGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                model.transform.localRotation = Quaternion.Euler(new Vector3(00, 180f));
            }
        });
        CreateEnemy.onClick.AddListener(() => //enemy 생성
        {
            if(!enemyExist)
            {
                float x = 1;
                for (int i = 0; i<5; i++)
                {
                    
                    GameObject enemyGO = new GameObject("enemy");
                    Enemy enemy = enemyGO.AddComponent<Enemy>();
                    enemyGO.transform.position = new Vector3(x, 3.38f, -1.7045f);
                    var model = Instantiate(enemyPrefab);
                    model.transform.SetParent(enemyGO.transform, false);
                    model.transform.localPosition = Vector3.zero;
                    enemy.model = model;                    
                    enemy.Attack();
                    x -= 0.5f;
                }
                enemyExist = true;
                
            }
        });
    }
 
    // Update is called once per frame
    void Update()
    {        
        if(GameObject.Find("enemy"== null)
        {
            enemyExist = false;
        }        
        if(ship != null)
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                if (ship.transform.position.x >= -1.96f)
                {
                    ship.transform.position += Vector3.left * 2 * Time.deltaTime;
                }
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                if (ship.transform.position.x <= 1.96f)
                    ship.transform.position += Vector3.right * 2 * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.UpArrow))
            {
                if (ship.transform.position.y <= 4.4f)
                    ship.transform.position += Vector3.up * 2 * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.DownArrow))
            {
                if (ship.transform.position.y >= -1.7f)
                    ship.transform.position += Vector3.down * 2 * Time.deltaTime;
            }
            if (Input.GetKeyDown(KeyCode.Space))
            {
                GameObject bulletGO = new GameObject("Bullet");
                bulletGO.transform.position = ship.bulletInitPoint.transform.position;
                Bullet bullet = bulletGO.AddComponent<Bullet>();
                var model = Instantiate(App.bulletPrefab);
                model.transform.SetParent(bulletGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                bullet.GoTo();
            }
        }
        
         
    }
}
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Ship : MonoBehaviour
{
    public GameObject bulletInitPoint;
 
    // Start is called before the first frame update
    void Start()
    {
        bulletInitPoint = new GameObject("bulletInitPoint");
        bulletInitPoint.transform.SetParent(this.transform, false);
        bulletInitPoint.transform.localPosition = new Vector3(00.4f, 0);
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.153413f, 0.46f, 1f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
    }
    private void OnTriggerEnter(Collider other)
    {
        Destroy(this.gameObject);
    }
 
    // 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Enemy : MonoBehaviour
{
    public Vector3 target;
    public GameObject model;
    private GameObject bulletInitPoint;
    // Start is called before the first frame update
    private void Awake()
    {
        bulletInitPoint = new GameObject("bulletInitPoint");
        bulletInitPoint.transform.SetParent(this.transform, false);
        bulletInitPoint.transform.localPosition = new Vector3(0-0.25f, 0);
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.3373507f, 0.34f, 0.2f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
    }
    private void OnTriggerEnter(Collider other)
    {
        Destroy(this.gameObject);
    }
    void Start()
    {
        
    }
    public void Attack()
    {
        StartCoroutine(AttackC());
    }
    IEnumerator AttackC()//자동공격
    {
        while(true)
        {
            if (GameObject.Find("Ship"!= null)
            {
                //bullet 생성                                             
                GameObject bulletGO = new GameObject("Bullet");
                bulletGO.transform.position = bulletInitPoint.transform.position;
                Bullet bullet = bulletGO.AddComponent<Bullet>();
                var model = Instantiate(App.bulletPrefab);
                model.transform.SetParent(bulletGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                target = GameObject.Find("Ship").transform.position;
                bullet.GoTo(target);//발사(비유도탄)   
            }
            yield return new WaitForSeconds(1f);
        }
    }
    // 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
71
72
73
74
75
76
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Bullet : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.07f, 0.07f, 0.2f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
        this.tag = "bullet";
    }
    public void GoTo(Vector3 target)
    {        
        StartCoroutine(GoToC(target));
    }
    public void GoTo()
    {
        StartCoroutine(GoToC());
    }
    IEnumerator GoToC()
    {        
        while (true)
        {
            this.transform.position += this.transform.up * 3 * Time.deltaTime;
            if (this.transform.position.x <= -1.96f || this.transform.position.x >= 1.96f || this.transform.position.y >= 4.4f || this.transform.position.y <= -1.7f)
            {
                Destroy(this.gameObject);
            }
            
            yield return null;
        }        
    }
    IEnumerator GoToC(Vector3 target)
    {
        var vc = (target - this.transform.position).normalized;
        while(true)
        {
            this.transform.position += vc * 1 * Time.deltaTime;
            if (this.transform.position.x <= -1.96f || this.transform.position.x >= 1.96f || this.transform.position.y >= 4.4f || this.transform.position.y <= -1.7f)
            {
                Destroy(this.gameObject);
            }
            //if (Vector3.Distance(target, this.transform.position) <= 0.01f)
            //{
            //    Destroy(this.gameObject);
            //}
            yield return null;
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag != "bullet")
        {
            GameObject explosionInst = Instantiate(App.explosion);
            explosionInst.transform.position = this.gameObject.transform.position;
            Destroy(this.gameObject);
        }
        
 
        
        
    }
 
    // 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class BGScroller : MonoBehaviour
{
    private MeshRenderer render;
    private float offset;
    public float speed;
    // Start is called before the first frame update
    void Start()
    {
        render = GetComponent<MeshRenderer>();
    }
 
    // Update is called once per frame
    void Update()
    {
        offset += Time.deltaTime * speed;
        render.material.mainTextureOffset = new Vector2(0, offset);
    }
}
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class explosion : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }
    void DestroyGO()
    {
        Destroy(this.gameObject);
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

explosion 스프라이트 애니메이션 만들기:

1. 스프라이트 png파일을 받아서 slice하여 sprite로 만든다.

2. gameobject를 하나 생성하여 Sprite Renderer 컴포넌트를 추가한 후에 Sprite에 생성한 explosion sprite를 드래그한다.

3. window창 -> animation으로 들어가 2번에서 만든 gameobject 선택후 클립 생성, sprite를 드래그하여 프레임을 씌운다. 

4. 원하는 프레임을 골라 이벤트를 추가한다.

5. 스크립트를 추가해 2번에서 만든 gameobject에 추가한 후 메서드를 생성, 4번에서 만든 프레임을 선택해 실행될 메서드(스크립트에있는)를 선택한다.

6.다시 프리팹화 하여 추후에 사용한다.

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

오브젝트 풀링 (인스턴스로 접근)  (0) 2019.12.16
12.10 오브젝트 풀 활용  (0) 2019.12.10
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
ref 와 out  (0) 2019.10.31
:

12.09 충돌감지와 sprite활용하기(delegate)

C#/실습 2019. 12. 9. 17:25

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
 
public class App : MonoBehaviour
{
    public Button btnShoot;
    public Transform bulletInitPoint;
    private GameObject bulletPrefab;
    private Sprite explosionsprite;
    
    // Start is called before the first frame update
    void Start()
    {
        this.LoadResources();
        this.btnShoot.onClick.AddListener(() =>
        {
            Debug.Log("발사!");
            this.Shoot();
 
        });
    }
    private void LoadResources()
    {
        this.bulletPrefab = Resources.Load<GameObject>("Bullet");
        this.explosionsprite = Resources.Load<Sprite>("explosion3");
 
    }
    private void Shoot()
    {
        GameObject bulletModel = Instantiate(bulletPrefab);
        Bullet bullet = bulletModel.AddComponent<Bullet>();
        bulletModel.transform.position = this.bulletInitPoint.position;
        bullet.ShootCoroutine = bullet.ShootImple();
        StartCoroutine(bullet.ShootCoroutine);
        bullet.del = () =>
        {
            StopCoroutine(bullet.ShootCoroutine);
            GameObject explosionGO = new GameObject("explosion");
            explosionGO.transform.position = bullet.transform.position;
            SpriteRenderer spriteRenderer = explosionGO.AddComponent<SpriteRenderer>();
            spriteRenderer.sprite = Instantiate(explosionsprite);
            Animator animator = explosionGO.AddComponent<Animator>();
            animator.runtimeAnimatorController = 
            (RuntimeAnimatorController)RuntimeAnimatorController.Instantiate(
            Resources.Load("ExplosionCon"typeof(RuntimeAnimatorController)));
            explosion explosion = explosionGO.AddComponent<explosion>();            
            Destroy(bullet.gameObject);
 
        };
        
        
        
        
    }
    
    
    // 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class explosion : MonoBehaviour
{
    public void whenExplode()
    {
        Destroy(this.transform.root.gameObject);
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }
 
    // 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Bullet : MonoBehaviour
{
    public Action del;
    public IEnumerator ShootCoroutine;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    //private void OnCollisionEnter(Collision collision)
    //{                
    //    App.del();        
    //}
    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "wall")
        {
            this.del();
        }
        
    }
    public IEnumerator ShootImple()
    {
        while (true)
        {
            var vc = this.transform.up;
            this.transform.position += vc * 1 * Time.deltaTime;
 
            yield return null;
        }
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

참조:

Sprite 파일

https://www.pngguru.com/free-transparent-background-png-clipart-zceay

 

Sprite GameMaker: Studio Animation 2D computer graphics, explosion sprite transparent background PNG clipart | PNGGuru

PNG Clipart Information Dimensions 960x384px File size 113.87KB MIME type Image/png dominant color orange Resize PNG Clipart online resize by width resize by height

www.pngguru.com

스프라이트 애니메이션

https://m.blog.naver.com/PostView.nhn?blogId=heartybrain1&logNo=221142037112&proxyReferer=https%3A%2F%2Fwww.google.com%2F

 

유니티 - 스프라이트 시트(sprite sheet) 사용하기, 스프라이트 애니메이션

유니티에서 sprite sheet 사용하기, sprite 애니메이션 1)스프라이트 시트(sprite sheet)는 2D 애니메이션...

blog.naver.com

코드에서 애니메이션 바꾸기

https://playground10.tistory.com/95

 

[유니티] 코드에서 애니메이션 바꾸기

프리팹은 하나이고 애니메이션만 계속 코드에서 동적으로 바꾸고 싶을 때 아래와 같이 해주면 됩니다. 1. 먼저 해당 프리팹에 animator 컴포넌트를 추가해줍니다. (기존에 프리팹을 Player라고 만들었고 스크립트..

playground10.tistory.com

 

:

2019.12.08 드래곤플라이트 과제

C#/과제 2019. 12. 8. 01:37

 

코드:

 

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App : MonoBehaviour
{
    public Ship ship;
    public Button CreateEnemy;
    public Button CreateShip;
    private bool enemyExist = false;
    private GameObject enemyPrefab;
    public static GameObject bulletPrefab;
    private GameObject shipPrefab;
    // Start is called before the first frame update
    private void Awake()
    {
        bulletPrefab = Resources.Load<GameObject>("fireball-blue-med");
        enemyPrefab = Resources.Load<GameObject>("ship1");
        shipPrefab = Resources.Load<GameObject>("ship2");
    }
    void Start()
    {
        CreateShip.onClick.AddListener(() =>
        {
            if(GameObject.Find("Ship"== null)
            {
                GameObject shipGO = new GameObject("Ship");
                ship = shipGO.AddComponent<Ship>();
                var model = Instantiate(shipPrefab);
                ship.transform.position = new Vector3(0-1.237f, -1.7045f);
                model.transform.SetParent(shipGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                model.transform.localRotation = Quaternion.Euler(new Vector3(00, 180f));
            }
        });
        CreateEnemy.onClick.AddListener(() => //enemy 생성
        {
            if(!enemyExist)
            {
                float x = 1;
                for (int i = 0; i<5; i++)
                {
                    
                    GameObject enemyGO = new GameObject("enemy");
                    Enemy enemy = enemyGO.AddComponent<Enemy>();
                    enemyGO.transform.position = new Vector3(x, 3.38f, -1.7045f);
                    var model = Instantiate(enemyPrefab);
                    model.transform.SetParent(enemyGO.transform, false);
                    model.transform.localPosition = Vector3.zero;
                    enemy.model = model;                    
                    enemy.Attack();
                    x -= 0.5f;
                }
                enemyExist = true;
                
            }
        });
    }
 
    // Update is called once per frame
    void Update()
    {        
        if(GameObject.Find("enemy"== null)
        {
            enemyExist = false;
        }        
        if(ship != null)
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                if (ship.transform.position.x >= -1.96f)
                {
                    ship.transform.position += Vector3.left * 2 * Time.deltaTime;
                }
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                if (ship.transform.position.x <= 1.96f)
                    ship.transform.position += Vector3.right * 2 * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.UpArrow))
            {
                if (ship.transform.position.y <= 4.4f)
                    ship.transform.position += Vector3.up * 2 * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.DownArrow))
            {
                if (ship.transform.position.y >= -1.7f)
                    ship.transform.position += Vector3.down * 2 * Time.deltaTime;
            }
            if (Input.GetKeyDown(KeyCode.Space))
            {
                GameObject bulletGO = new GameObject("Bullet");
                bulletGO.transform.position = ship.bulletInitPoint.transform.position;
                Bullet bullet = bulletGO.AddComponent<Bullet>();
                var model = Instantiate(App.bulletPrefab);
                model.transform.SetParent(bulletGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                bullet.GoTo();
            }
        }
        
         
    }
}
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class BGScroller : MonoBehaviour
{
    private MeshRenderer render;
    private float offset;
    public float speed;
    // Start is called before the first frame update
    void Start()
    {
        render = GetComponent<MeshRenderer>();
    }
 
    // Update is called once per frame
    void Update()
    {
        offset += Time.deltaTime * speed;
        render.material.mainTextureOffset = new Vector2(0, offset);
    }
}
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Ship : MonoBehaviour
{
    public GameObject bulletInitPoint;
 
    // Start is called before the first frame update
    void Start()
    {
        bulletInitPoint = new GameObject("bulletInitPoint");
        bulletInitPoint.transform.SetParent(this.transform, false);
        bulletInitPoint.transform.localPosition = new Vector3(00.4f, 0);
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.153413f, 0.46f, 1f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
    }
    private void OnTriggerEnter(Collider other)
    {
        Destroy(this.gameObject);
    }
 
    // 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Enemy : MonoBehaviour
{
    public Vector3 target;
    public GameObject model;
    private GameObject bulletInitPoint;
    // Start is called before the first frame update
    private void Awake()
    {
        bulletInitPoint = new GameObject("bulletInitPoint");
        bulletInitPoint.transform.SetParent(this.transform, false);
        bulletInitPoint.transform.localPosition = new Vector3(0-0.25f, 0);
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.3373507f, 0.34f, 0.2f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
    }
    private void OnTriggerEnter(Collider other)
    {
        Destroy(this.gameObject);
    }
    void Start()
    {
        
    }
    public void Attack()
    {
        StartCoroutine(AttackC());
    }
    IEnumerator AttackC()//자동공격
    {
        while(true)
        {
            if (GameObject.Find("Ship"!= null)
            {
                //bullet 생성                                             
                GameObject bulletGO = new GameObject("Bullet");
                bulletGO.transform.position = bulletInitPoint.transform.position;
                Bullet bullet = bulletGO.AddComponent<Bullet>();
                var model = Instantiate(App.bulletPrefab);
                model.transform.SetParent(bulletGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                target = GameObject.Find("Ship").transform.position;
                bullet.GoTo(target);//발사(비유도탄)   
            }
            yield return new WaitForSeconds(1f);
        }
    }
    // 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
71
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Bullet : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.07f, 0.07f, 0.2f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
        this.tag = "bullet";
    }
    public void GoTo(Vector3 target)
    {        
        StartCoroutine(GoToC(target));
    }
    public void GoTo()
    {
        StartCoroutine(GoToC());
    }
    IEnumerator GoToC()
    {        
        while (true)
        {
            this.transform.position += this.transform.up * 3 * Time.deltaTime;
            if (this.transform.position.x <= -1.96f || this.transform.position.x >= 1.96f || this.transform.position.y >= 4.4f || this.transform.position.y <= -1.7f)
            {
                Destroy(this.gameObject);
            }
            
            yield return null;
        }        
    }
    IEnumerator GoToC(Vector3 target)
    {
        var vc = (target - this.transform.position).normalized;
        while(true)
        {
            this.transform.position += vc * 1 * Time.deltaTime;
            if (this.transform.position.x <= -1.96f || this.transform.position.x >= 1.96f || this.transform.position.y >= 4.4f || this.transform.position.y <= -1.7f)
            {
                Destroy(this.gameObject);
            }
            //if (Vector3.Distance(target, this.transform.position) <= 0.01f)
            //{
            //    Destroy(this.gameObject);
            //}
            yield return null;
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag != "bullet")
            Destroy(this.gameObject);
 
        
        
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

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

12.16 토글 버튼 만들기  (0) 2019.12.16
:

12.06 드래곤플라이트 구현

C#/실습 2019. 12. 6. 17:16

코드:

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Ship : MonoBehaviour
{
    public Transform bulletInitPoint;
    public Vector3 targetV;
    public GameObject model;
    GameObject prefab;
    GameObject modelBullet;
 
    // Start is called before the first frame update
    void Start()
    {
        prefab = Resources.Load<GameObject>("Prefabs/fireball-blue-big");
    }
    public void Attack()
    {
        StartCoroutine("MakeBulletForward");
        StartCoroutine("MakeBulletSide1");
        StartCoroutine("MakeBulletSide2");
 
    }
    IEnumerator MakeBulletSide1()
    {
        while (true)
        {
            GameObject bulletGO = new GameObject("bullet");
            bulletGO.transform.position = bulletInitPoint.position;
            Bullet bullet = bulletGO.AddComponent<Bullet>();
            modelBullet = Instantiate(prefab);
 
            modelBullet.transform.SetParent(bulletGO.transform, false);
            modelBullet.transform.localPosition = Vector3.zero;
            bullet.MoveSide1();
            yield return new WaitForSeconds(1f);
        }
    }
    IEnumerator MakeBulletSide2()
    {
        while (true)
        {
            GameObject bulletGO = new GameObject("bullet");
            bulletGO.transform.position = bulletInitPoint.position;
            Bullet bullet = bulletGO.AddComponent<Bullet>();
            var model = Instantiate(prefab);
            model.transform.SetParent(bulletGO.transform, false);
            model.transform.localPosition = Vector3.zero;
            bullet.MoveSide2();
            yield return new WaitForSeconds(1f);
        }
    }
 
    IEnumerator MakeBulletForward()
    {
        while(true)
        {
            GameObject bulletGO = new GameObject("bullet");           
            bulletGO.transform.position = bulletInitPoint.position;
            Bullet bullet = bulletGO.AddComponent<Bullet>();
            var model = Instantiate(prefab);
            model.transform.SetParent(bulletGO.transform, false);
            model.transform.localPosition = Vector3.zero;
            bullet.Move();
            yield return new WaitForSeconds(1f);
        }
        
        
    }
    
    
    // Update is called once per frame
    void Update()
    {
        {
            if(this.transform.position.x >= -3.5f)
            {
                this.transform.position += Vector3.left * 2 * Time.deltaTime;
            }
        }
        {
            if (this.transform.position.x <= 3.5f )
                this.transform.position += Vector3.right * 2 * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.UpArrow))
        {
            if ( this.transform.position.y <= 6f)
                this.transform.position += Vector3.up * 2 * Time.deltaTime;
        }
        {
            if (this.transform.position.y >= -6f )
                this.transform.position += Vector3.down * 2 * Time.deltaTime;
        }
    }
}
 
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
71
72
73
74
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Bullet : MonoBehaviour
{
    Coroutine coroutineMove;
    // Start is called before the first frame update
    void Start()
    {
    }
    public void Move()
    {
        coroutineMove = StartCoroutine("MoveC");
 
    }
    public void MoveSide2()
    {
        StartCoroutine("MoveSideC2");
        StartCoroutine("MoveC");
    }
    IEnumerator MoveSideC2()
    {
        while (true)
        {
            var speed = 2;
 
            this.transform.position += -this.transform.right * speed * Time.deltaTime;
            if (this.transform.position.y >= 6f || this.transform.position.x <= -3.6f || this.transform.position.x >= 3.6f)
            {
                Destroy(this.gameObject);
            }
            yield return null;
        }
    }
    public void MoveSide1()
    {
        StartCoroutine("MoveSideC1");
        StartCoroutine("MoveC");
    }
    IEnumerator MoveSideC1()
    {
        while (true)
        {
            var speed = 2;
 
            this.transform.position += this.transform.right * speed * Time.deltaTime;
            if (this.transform.position.y >= 6f || this.transform.position.x <= -3.6f || this.transform.position.x >= 3.6f)
            {
                Destroy(this.gameObject);
            }
            yield return null;
        }
    }
    IEnumerator MoveC()
    {
        while (true)
        {
            var speed = 2;
            this.transform.position += this.transform.up * speed * Time.deltaTime;
            if (this.transform.position.y >= 6f)
            {
                Destroy(this.gameObject);
            }
            yield return null;
        }
    }
    // 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App2 : MonoBehaviour
{
    public Ship ship;
    public Button btnAttack;
    // Start is called before the first frame update
    void Start()
    {
        btnAttack.onClick.AddListener(() =>
        {
            ship.Attack();
        });
    }
 
    // 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class BGScroller : MonoBehaviour
{
    private MeshRenderer render;
    private float offset;
    public float speed;
    // Start is called before the first frame update
    void Start()
    {
        render = GetComponent<MeshRenderer>();
    }
 
    // Update is called once per frame
    void Update()
    {
        offset += Time.deltaTime * speed;
        render.material.mainTextureOffset = new Vector2(0, offset);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

참조:

무한 스크롤 배경:https://www.youtube.com/watch?v=asraLkuR3Jg

:

12.05 유닛 바라보기 (LookAt 메서드 사용X)

C#/실습 2019. 12. 5. 17:28

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
 
public class App2 : MonoBehaviour
{
    public GameObject model1;
    public GameObject model2;
    public Button btn;
    float angle;
    // Start is called before the first frame update
    void Start()
    {
        btn.onClick.AddListener(() =>
        {
 
            angle = Vector3.Angle(model2.transform.position - model1.transform.position, model1.transform.forward);
            Debug.Log(angle);
            if (Vector3.Dot(model1.transform.right, model2.transform.position - model1.transform.position) >= 0f)
            {
                model1.transform.rotation = model1.transform.rotation * Quaternion.Euler(0, angle, 0);
            }
            else
            {
                model1.transform.rotation = model1.transform.rotation * Quaternion.Euler(0-angle, 0);
 
            }
 
 
        });
    }
 
    // Update is called once per frame
    void Update()
    {
        //Debug.Log(angle);
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

그냥 A 와 B사이의 벡터를 구하고 A가 바라보는 벡터의 각을 구하기엔 B가 A의 오른쪽에 있든 왼쪽에 있든 같은 angle값이 나오기때문에 구분이 불가능했다.

따라서 A의 right 벡터와 A,B사이 벡터의 내적을 구하고 이것이 0보다 큰지 작은지를 비교해 이를 해결했다.

:

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
:

11.29 캐릭터 움직이기 (Coroutine, Update 비교 및 활용)

C#/실습 2019. 11. 29. 16:11

Move(Coroutine)을 누른후

코드:

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
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);
        }
    }
 
    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
 
: