C#/수업내용

2020.05.08. 수업내용 - 벡터(단위벡터)

dev_sr 2020. 5. 10. 22:29

 

벡터를 이용하면 직선방향 뿐만이 아니라 어떠한 방향도 이동할 수 있다.

 

벡터 : 크기와 방향
단위벡터 : 길이(magnitude) 가 1인 벡터 (비교하기 쉽게하기 위해서 사용)
길이는 항상 양수이다.

 

//빼는 순서에 따라 양수나 음수가 나온다.

Vector3 c = this.hero.transform.position - this.monster.transform.position;


//벡터의 길이 출력
Debug.Log(c.magnitude);

//벡터의 정규화(단위벡터로 만들기-길이를 1로 만들기) 출력
Debug.Log(c.normalized);

 

 

1. App

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
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;
using UnityEngine.UI;
 
public class App : MonoBehaviour
{
    public GameObject hero;
    public GameObject monster;
    public Button btn;
    public float speed;
 
    private Animation anim;
    private bool isRun;
    private Vector3 dir { get; set; }
 
 
    private void Start()
    {
        this.anim = this.hero.GetComponent<Animation>();
        this.btn.onClick.AddListener(() =>
        {
            this.Run();
        });
    }
 
    private void Run()
    {
        this.PlayAnimation("run@loop");
        this.isRun = true;
    }
 
    private void Idle()
    {
        this.PlayAnimation("idle@loop");
        this.isRun = false;
    }
 
    private void PlayAnimation(string animation)
    {
        this.anim.Play(animation);
    }
 
    private void Update()
    {
        if (this.isRun == true)
        {
            float distance = Vector3.Distance(this.hero.transform.position, this.monster.transform.position);
            this.dir = this.monster.transform.position - this.hero.transform.position;
 
            //단위벡터를 구하지 않으면 몬스터와 가까울 때 빨라지고
            //멀어지면 다시 빨라진다.
            var nordir = this.dir.normalized;
 
            this.hero.transform.Translate(this.speed * Time.deltaTime * nordir);
            Debug.Log(distance);
 
            if (distance <= 0.035f)
            {
                this.Idle();
            }
 
        }
 
    }
 
}