유니티3D 프로그래밍
Unity 5주차 4일 수업 내용 : Ray, 캐릭터 이동 (21.04.08) 본문
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);
}
}
}
}
'Unity > 수업내용' 카테고리의 다른 글
Unity UGUI Test (21.04.20) (0) | 2021.04.20 |
---|---|
Unity 6주차 5일 수업 내용 : 다단계 Scene 구성 (21.04.06) (0) | 2021.04.16 |
Unity 6주차 3,4,5일 수업 내용 : Zombie (21.04.14) (0) | 2021.04.16 |
Unity 6주차 2일 수업 내용 : 쿠키런 구현해보기 (21.04.13) (0) | 2021.04.13 |
Unity 5주차 5일 수업 내용 : Dodge, Fov (21.04.09) (0) | 2021.04.09 |