沿引导路径行驶 [英] Traversing along guided path

查看:97
本文介绍了沿引导路径行驶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var distancesquared = (transform.position - currentpath.Current.position).sqrMagnitude;
if (distancesquared < 0.1f * 0.1f)
    currentpath.MoveNext ();

我已经使用统一的变换数组创建了一条要遵循的路径,现在,如果我不使用上面的if语句而只是执行currentpath.MoveNext(),它只会沿着第一对点移动并且不会越过要完成路径,请问该if语句与遍历路径有什么关联?

I have created a path to be followed using an array of Transforms in unity, now If I do not use the above if statement and just do currentpath.MoveNext(), it just traverses along first pair of points and does not go one beyond to complete the path, what is the co relation of this if statement with traversing the path, Please?

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

public class followpath : MonoBehaviour {

    public enum followtype
    {
        movetowards,
        lerp
    }
    public followtype type = followtype.movetowards;
    public Pathdefinition path;
    public float speed = 1;
    public float maxdistancetodo = 0.1f;

    private IEnumerator<Transform>  currentpath;
    public void Start()
    {
        if (path == null)
        {
            Debug.LogError ("path can not be null", gameObject);
            return;
        }
        currentpath = path.getpathenumerator ();
        currentpath.MoveNext ();
        if (currentpath.Current == null)
            return;

        transform.position = currentpath.Current.position;
    }

    public void Update()
    {
        if (currentpath == null || currentpath.Current == null)
            return;
        if (type == followtype.movetowards)
            transform.position = Vector3.MoveTowards (transform.position, currentpath.Current.position, Time.deltaTime * speed);
        else if (type == followtype.lerp)
            transform.position = Vector3.Lerp (transform.position, currentpath.Current.position, Time.deltaTime * speed);


        var distancesquared = (transform.position - currentpath.Current.position).sqrMagnitude;
        if (distancesquared < maxdistancetodo* maxdistancetodo)
            currentpath.MoveNext ();
    }
}

推荐答案

在更新代码时,它会执行每一帧.

When you put code in update, it executes every frame.

if语句在迭代到路径中的下一个目标点之前检查以确保您的对象与当前目标位置足够近.

The if statement checks to make sure your object is near enough to it's current target position before iterating to the next target point in the path.

如果没有if语句,则每一帧都会导致路径上的下一个停靠点被加载到迭代器中.这发生在您的对象有机会接近其先前目标之前.此外,由于帧发生得如此之快,这意味着整个路径将在不到一秒钟的时间内被遍历,并且对象在设法走得很远之前就停止了移动.

Without your if statement, each frame will cause the next stop on the path to be loaded in the iterator. This occurs before your object has had a chance to get near its previous target. Additionally, since frames occur so quickly, it means the entire path is iterated over in less than a second, and the object stops moving before it's managed to go very far.

这篇关于沿引导路径行驶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆