在 Unity 开发 VR 内容时,我想创建一个脚本,在移动到 Waypoint 路线时在最后一个 Waypoint 停止,但是我在 C# Coding 方面有非常基本的技能,(我尽力了,但我失败了)所以我想向你寻求帮助...
这是回到第一个航点的脚本,你能帮我吗?我真的很感谢你的帮助。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCtrl : MonoBehaviour
{
//이동방식 열거형 변수 선언
public enum MoveType
{
WAY_POINT,
LOOK_AT,
DAYDREAM
}
//이동방식
public MoveType moveType = MoveType.WAY_POINT;
//이동속도
public float speed = 1.0f;
//회전속도
public float damping = 3.0f;
public int zero = 0;
//모든 웨이포인트를 저장할 배열
public Transform[] points;
//트랜스톰 컴포넌트를 저장할 변수
private Transform tr;
//다음에 이동해야할 위치 인덱스 변수
private int nextIdx = 1;
void Start()
{
//트랜스폼 컴포넌트 추출후 변수 저장
tr = GetComponent<Transform>();
//포인트 게임오브젝트를 검색해 변수에 저장
GameObject WayPointGroup = GameObject.Find("WayPointGroup");
if(WayPointGroup != null)
{
//웨이포인트 하위에 모든 게임 오브젝트 Transfotm 컴포넌트 추출
points = WayPointGroup.GetComponentsInChildren<Transform>();
}
}
// Update is called once per frame
void Update()
{
switch (moveType)
{
case MoveType.WAY_POINT:
MoveWayPoint();
break;
case MoveType.LOOK_AT:
break;
case MoveType.DAYDREAM:
break;
}
}
//웨이포인트 경로로 이동하는 로직
void MoveWayPoint()
{
//현재 위치에서 다음 웨이포인트로 향하는 벡터를 계산
Vector3 direction = points[nextIdx].position - tr.position;
//산출된 벡터의 회전 각도를 쿼터니언 타입으로 산출
Quaternion rot = Quaternion.LookRotation(direction);
//현재 각도에서 회전해야 할 각도까지 부드럽게 회전처리
tr.rotation = Quaternion.Slerp(tr.rotation, rot, Time.deltaTime * damping);
//전진 방향으로 이동처리
tr.Translate(Vector3.forward * Time.deltaTime * speed);
}
void OnTriggerEnter(Collider coll)
{
//웨이포인트 - 포인트 게임 오브텍트 충돌여부 판단
if (coll.CompareTag("WAY_POINT"))
{
//맨 마지막 웨이포인트에 도달했을 때 처음 인덱스로 변경
nextIdx = (++nextIdx >= points.Length) ? 1 : nextIdx;
}
}
}