0

在 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;
           
        }

        
      

    }

 
}

4

1 回答 1

0

好的,我不确定这个脚本是否是预定义的。

但是您的问题背后的策略非常简单。

  • 创建一个始终包含最后一个航路点的变量
  • 编写逻辑以在到达下一个航点时覆盖它
  • 到达最后一个航路点后也将其设置为空。
  • 并且在设置航点时(航点!= null)然后向航点移动。

我这样描述它是因为有很多方法可以完成这个航点系统——要有创意。

还..

为了简化您的代码,我将使用 Vector3.moveTowards() 和 transform.lookAt() 方法。有了这些,您可以轻松实现目标。

Vector3.MoveTowards() 以给定的时间*速度将对象从一个点移动到另一个点

transform.LookAt(DestTransform) 使当前的Transforms 正z 轴看transfrom 的方向。如果这不符合您的需要,请尝试在之后修改变换而不是复杂的旋转操作。

于 2020-08-21T08:05:46.313 回答