微元法实现路径行走 1.避免了行走speed过快导致闪烁 2.而不是直接moveTo 3.思考离散模拟连续世界的思路

本文介绍了一个Unity中的路径导航实现方案,使用自定义的nav_move类,通过PathManager获取路径点,利用WaypointManager生成平滑路径,实现了角色沿路径移动的功能。文章详细解释了关键变量的作用,如speed控制移动速度,walk_time和passed_time确保了移动过程的流畅性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

public class nav_move : MonoBehaviour {
    public bool play_on_load = false;
    public PathManager path;
    private Vector3[] road_data = null;
    private int next_step = 0;
    private float speed = 50000.0f; // 速度过快也没用
    private float walk_time = 0.0f;
    private float passed_time = 0.0f;
    private bool is_walking = false;

	// Use this for initialization
	void Start () {
        Vector3[] ctrl_points = path.GetPathPoints();
        this.road_data = WaypointManager.GetCurved(ctrl_points);
        if (this.play_on_load) {
            this.walk_on_road();
        }
    }

    void walk_on_road()
    {
        if (this.road_data.Length < 2)
        {
            return;
        }

        this.transform.position = this.road_data[0];
        this.next_step = 1;
        this.walk_to_next();
    }

    void walk_to_next()
    {
        if (this.next_step >= this.road_data.Length)
        {
            this.is_walking = false;
            return;
        }

        Vector3 src = this.transform.position;
        Vector3 dst = this.road_data[this.next_step];
        Vector3 dir = dst - src;
        float len = dir.magnitude;
        if (len <= 0)
        {
            this.next_step++;
            this.walk_to_next();
            return;
        }

        this.is_walking = true;
        this.walk_time = len / this.speed;
        this.passed_time = 0;
        this.transform.LookAt(dst);
    }

    // Update is called once per frame
    void Update () {
        if (!this.is_walking)
        {
            return;
        }
        float dt = Time.deltaTime;
        this.passed_time += dt;

        float real_walk_time = 0;
        if (this.passed_time > this.walk_time)
        {
            real_walk_time = dt - (this.passed_time - this.walk_time); // 避免速度过快时跳跃
        }
        else
        {
            real_walk_time = dt;
        }

        float s = this.speed * real_walk_time;
        this.transform.Translate(this.transform.forward * s , Space.World);
        if (this.passed_time >= this.walk_time)
        {
            this.next_step++;
            this.walk_to_next();
        }
	}
}

real_walk_time 的存在,如果speed过快,会被拉回来,所以没关系

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值