유니티 기초
간단 RPG
EasyCastleT
2023. 8. 8. 14:42
1.코루틴 이용 오브젝트 이용(애니메이션 포함)
HeroController (아직 Test여서 namespace Test에다가 정의하여 사용함)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Test
{
public class HeroController : MonoBehaviour
{
private Vector3 targetPosition;
private Coroutine moveRoutine;
private Animator anim;
// Start is called before the first frame update
void Start()
{
this.anim = this.GetComponent<Animator>();
}
public void Move(Vector3 targetPosition)
{
//이동 애니메이션 실행
this.anim.SetInteger("State", 1);
//이동할 목표 지점을 저장
this.targetPosition = targetPosition;
if(this.moveRoutine != null)
{
//이미 코루틴이 실행중이다 -> 중지
this.StopCoroutine(this.moveRoutine);
}
this.moveRoutine = StartCoroutine(this.CoMove());
}
private IEnumerator CoMove()
{
while (true)
//무한 반복이 되어 유니티가 멈출 수도 있음
//그러므로 yield return 필수
{
//방향을 바라봄
this.transform.LookAt(targetPosition);
//이미 바라봤으니깐 정면으로 이동 (relateTo: Self/지역좌표)
//방향 * 속도 * 시간
this.transform.Translate(Vector3.forward * 2f * Time.deltaTime);
//목표지점과 나 사이의 거리를 계산, 즉 1프레임 마다 거리를 계산
float distance = Vector3.Distance(this.transform.position, this.targetPosition);
if (distance <= 0.1f)
{
//도착
this.anim.SetInteger("State", 0);
break;
}
yield return null; //다음 프레임 시작
}
Debug.Log("<color=yellow>도착!</color>");
}
}
}
Test_PlayerControlSceneMain
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Test;
public class Test_PlayerControlSceneMain : MonoBehaviour
{
[SerializeField]
private HeroController heroController;
[SerializeField]
private Image image;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//화면을 클릭하면 클릭한 위치로 Hero가 이동
if(Input.GetMouseButtonDown(0))
{
//Ray를 만든다
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float maxDistance =1000f;
//화면에 출력
Debug.DrawRay(ray.origin, ray.direction* maxDistance, Color.red,2f);
//충돌검사
RaycastHit hit;
if(Physics.Raycast(ray, out hit, maxDistance))
{
//충돌정보가 hit 변수에 담김
Debug.Log(hit.point); //월드 상의 충돌 지점 위치
//Hero Gameobject 이동
this.heroController.Move(hit.point);
}
}
}
}