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
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public Hero hero;
public GameObject flag;
private void Start()
{
DataManager.Instance.LoadData();
this.hero.Init(100);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 1000f, Color.red, 1f);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100f))
{
Debug.Log(hit.point);
this.flag.transform.position = hit.point;
this.hero.SetTarget(hit.point);
}
}
}
}
|
cs |
Test.cs
움직일 hero, 좌표를 확인할 flag.
카메라에서 마우스 좌표로 광선을 쏘고 collider와 충돌이 있다면 RaycastHit 발생.
해당 좌표를 읽어 히어로에 targetPosition으로 세팅.
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
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hero : MonoBehaviour
{
private GameObject model;
private Animation anim;
private Vector3 targetPos;
public void Init(int id)
{
var data = DataManager.Instance.GetDataById<CharacterData>(id);
this.model = Instantiate(Resources.Load<GameObject>("Prefabs/" + data.res_name));
this.model.transform.SetParent(this.transform, false);
this.anim = this.model.GetComponent<Animation>();
this.anim.Play("idle@loop");
}
public void SetTarget(Vector3 position)
{
this.targetPos = position;
this.transform.LookAt(new Vector3(position.x, this.transform.position.y, position.z));
}
private void Update()
{
if(Vector3.Distance(this.transform.position, targetPos) < 0.03f)
{
this.anim.Play("idle@loop");
}
else
{
this.anim.Play("run@loop");
this.transform.position += this.transform.forward * Time.deltaTime * 1.0f;
}
}
}
|
cs |
Hero.cs
아이디를 받아 모델 동적 생성.
targetPosition을 받으면 해당 방향을 바라보도록 설정.
update시에 거리가 멀다면 이동을, 가깝다면 idle을 실행.
Unity Study_017 2D, 애니메이터, 콜라이더 (0) | 2020.05.27 |
---|---|
Unity Study_015 HudText, Coroutine (0) | 2020.05.26 |
Unity Study_013-1 로그인 구현 (0) | 2020.05.22 |
Unity Study_007 무기변경, 닭 잡기. (0) | 2020.05.14 |
Unity Study_006 Effect and WeaponChange (0) | 2020.05.13 |