유니티 기초
rpg monster 복습
노재두내
2023. 8. 8. 22:18
main으로 관리하는것이 익숙하지 않음
main이름의 빈 오브젝트를 만들고 main 스크립트를 집어넣는다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Main : MonoBehaviour
{
[SerializeField]
private GameObject heroGo;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//ray 쏘는건 main에서
if (Input.GetMouseButtonDown(0))
{
Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue,3f);
RaycastHit hit;
if(Physics.Raycast(ray,out hit, 100f))
{
this.heroGo.transform.position = hit.point;
}
}
}
}
hit.point위치로 hero gameobject의 위치를 이동시킨다.
hero 게임오브젝트를 집어넣는다
-----------------------------------------------------------------------------------
불러오기(?) 연습
1.
[SerializeField]
private GameObject heroGo;
private DogController dogController;
// Start is called before the first frame update
void Start()
{
this.dogController = heroGo.GetComponent<DogController>();
}
2.
[SerializeField]
private DogController dogController;
// Start is called before the first frame update
void Start()
{
var heroGo = GameObject.Find("Hero");
this.dogController = heroGo.GetComponent<DogController>();
}
3.
private DogController dogController
모두 같음
this.dogController.Move(hit.point);
public void Move(Vector3 targetposition)
{
this.transform.position = targetposition;
}
hit.point를 인자로 , targetposition을 매개변수로
코루틴(coroutine) 연습
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Test
{
public class DogController : MonoBehaviour
{
private Vector3 targetPosition;
private Coroutine moveRoutine;
private Animator anim;
void Start()
{
this.anim = this.GetComponent<Animator>();
}
public void Move(Vector3 targetPosition)
{
this.targetPosition = targetPosition;
Debug.Log("Move");
this.anim.SetInteger("walk", 1);
if (this.moveRoutine != null)
{
this.StopCoroutine(this.moveRoutine);
}
this.moveRoutine = this.StartCoroutine(this.CoMove());
}
private IEnumerator CoMove()
{
while (true)
{
this.transform.LookAt(this.targetPosition);
this.transform.Translate(Vector3.forward * 1f * Time.deltaTime);
float distance = Vector3.Distance(this.transform.position, this.targetPosition);
Debug.Log(distance);
if (distance <= 0.1f)
{
break;
}
yield return null;
}
this.anim.SetInteger("walk", 0);
}
}
}