벡터를 이용하면 직선방향 뿐만이 아니라 어떠한 방향도 이동할 수 있다.
벡터 : 크기와 방향
단위벡터 : 길이(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();
}
}
}
}
|
'C# > 수업내용' 카테고리의 다른 글
2020.05.11 수업내용 - Scene 변환 (0) | 2020.05.11 |
---|---|
2020.05.08. 수업내용 - Unity Monobehaviour LifeCycle (0) | 2020.05.10 |
2020.05.07. 수업내용 - 지정된 위치에 몬스터와 캐릭터 생성시키기 (0) | 2020.05.08 |
2020.05.07. 수업내용 - Unity 버튼, 이동, 애니메이션 실행 (0) | 2020.05.08 |
2020.05.06. 수업내용 - Unity 캐릭터 이동시키기 (0) | 2020.05.06 |