본문 바로가기

정리 카테고리/실습_과제

실습_Unity_랜덤목표 따라가는 캐릭터

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;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Character : MonoBehaviour {
 
    private Vector3 targetPostion;
    public Transform target;
    private Vector3 moveV = new Vector3(000.9f);
     private System.Random random = new System.Random();
    bool chek = false;
    void Start () {
        
    }
 
 
    void Update()
    {
        Debug.Log(this.targetPostion);
        var distance = Vector3.Distance(this.targetPostion, this.transform.position);
        if (chek)
        {
            //Debug.Log(chek);
            var anm = this.GetComponent<Animation>();
            anm.Play("sit_idle@loop");
            ReSet();
        }
        else
        {
            var anm = this.GetComponent<Animation>();
            anm.Play("run@loop");
            //Debug.Log(targetPostion);
            Vector3 v33 = targetPostion - this.transform.position;
            float ta = Mathf.Atan2(v33.x, v33.z) * Mathf.Rad2Deg;
            ta = Mathf.LerpAngle(this.transform.eulerAngles.y, ta, Time.deltaTime * 180f);
            //Debug.Log(ta);
            this.transform.eulerAngles = new Vector3(0, ta, 0);
 
            //Debug.Log(this.transform.rotation);
            //this.transform.Translate(((targetPostion- this.transform.position)*Time.deltaTime ),Space.World);
            this.transform.Translate((moveV  * Time.deltaTime), Space.Self);
 
            //Debug.Log(distance);
            if (distance <=0.1f  ) chek = true;
 
        }
    }
    public void SetTargetPostion(Transform v3)
    {
        targetPostion = v3.position;
        target = v3;
    }
    public void ReSet()
    {
        float xPoint = (float)random.Next(115);
        float zPoint = (float)random.Next(115);
        //Debug.Log(zPoint);
        target.transform.position= new Vector3((xPoint * 1.1f), 0.0f, (zPoint * 1.1f));
        this.targetPostion = target.transform.position;
        Debug.Log(targetPostion);
        chek = false;
        //Debug.Log(chek);
    }
 
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Test01 : MonoBehaviour {
    public Character queryJJang;
    public Transform targetPosrion;
    // Use this for initialization
    void Start () {
      
    }
    
    // Update is called once per frame
    void Update () {
        queryJJang.SetTargetPostion(targetPosrion);
    }
}
 
cs