유니티3D 프로그래밍

Unity 5주차 4일 수업 내용 : Ray, 캐릭터 이동 (21.04.08) 본문

Unity/수업내용

Unity 5주차 4일 수업 내용 : Ray, 캐릭터 이동 (21.04.08)

tjdgus9955 2021. 4. 8. 17:33

Hero

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hero : MonoBehaviour
{
    public GameObject model;
    public float moveSpeed = 2f;

    private Vector3 targetPosition;
    private bool isMove;
    public Animation anim;
    public void Init()
    {
        //초기화
        this.anim = this.model.GetComponent<Animation>();
    }
    public void Move(Vector3 targetPosition)
    {
        this.targetPosition = targetPosition;
        //방향전환
        this.transform.LookAt(this.targetPosition);
        //애니메이션 
        this.anim.Play("run@loop");
        //이동시작
        this.isMove = true;
    }

    private void Update()
    {
        //이동
        if(this.isMove)
        {
            //이동
            //방향 * 속도 * 시간(Time.deltaTime)
            this.transform.Translate(0, 0, moveSpeed * Time.deltaTime);
            //거리
            var distace = Vector3.Distance(this.targetPosition, this.transform.position);
            if(distace < 0.1f)
            {
                //목표지점까지 다 왔다면 
                this.isMove = false;
                //애니메이션 
                this.anim.Play("idle@loop");
            }
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InGame : MonoBehaviour
{
    public Hero hero;

    private void Start()
    {
        this.hero.Init();
    }

    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay(ray.origin, ray.direction * 1000, Color.red, 1.5f);
            RaycastHit hit;
            if( Physics.Raycast(ray, out hit, 1000))
            {
                Debug.Log(hit.point);   // 충돌 위치 (타겟 위치)

                this.hero.Move(hit.point);
            }
        }
    }
}