纳金网
标题:
关于unity3d路径跟随的代码分享
[打印本页]
作者:
天国皇帝
时间:
2017-3-2 14:47
标题:
关于unity3d路径跟随的代码分享
关于如何设置简单的路径跟随;
最简单的路径更随方式是将当前路径点设置为路点,用靠近行为产生操控力来靠近路点直到非常考究这个点;然后寻找下一个路点,设置为当前路点,重复此过程,直到最后一个路点。
代码设置如下:using UnityEngine;using System.Collections;
public class SteeringFollowPath : Steering
{
public GameObject[] waypoints = new GameObject[4];
private Transform target;
private int currentNode;
private float arriveDistance;
private float sqrArriveDistance;
private int numberOfNodes;
private Vector3 force;
private Vector3 desiredVelocity;
private Vehicle m_vehicle;
private float maxSpeed;
private bool isPlanar;
public float slowDownDistance;
void Start ()
{
numberOfNodes = waypoints.Length;
m_vehicle = GetComponent<Vehicle>();
maxSpeed = m_vehicle.maxSpeed;
isPlanar = m_vehicle.isPlanar;
currentNode = 0;
target = waypoints[currentNode].transform;
arriveDistance = 1.0f;
sqrArriveDistance = arriveDistance * arriveDistance;
}
/*
public override Vector3 Force()
{
force = new Vector3(0,0,0);
Vector3 dist = transform.position - target.position;
//Vector3 dist = target.position - transform.position;
if (isPlanar)
dist.y = 0;
if (currentNode == numberOfNodes - 1)
{
print("now the last point!");
if (dist.magnitude > slowDownDistance)
{
desiredVelocity = (-dist.normalized) * maxSpeed;
force = desiredVelocity - m_vehicle.velocity;
}
else
{
desiredVelocity = (-dist) - m_vehicle.velocity;
force = desiredVelocity - m_vehicle.velocity;
}
return force;
}
if (dist.sqrMagnitude < sqrArriveDistance)
{
if ( currentNode < numberOfNodes -1)
{
currentNode ++;
target = waypoints[currentNode].transform;
}
}
desiredVelocity = (target.position - transform.position).normalized * maxSpeed;
if (isPlanar)
desiredVelocity.y = 0;
force = desiredVelocity - m_vehicle.velocity;
return force;
}*/
public override Vector3 Force()
{
force = new Vector3(0,0,0);
Vector3 dist = target.position - transform.position;
if (isPlanar)
dist.y = 0;
if (currentNode == numberOfNodes - 1)
{
if (dist.magnitude > slowDownDistance)
{
desiredVelocity = dist.normalized * maxSpeed;
force = desiredVelocity - m_vehicle.velocity;
}
else
{
desiredVelocity = dist - m_vehicle.velocity;
force = desiredVelocity - m_vehicle.velocity;
}
}
else
{
if (dist.sqrMagnitude < sqrArriveDistance)
{
currentNode ++;
target = waypoints[currentNode].transform;
}
desiredVelocity = dist.normalized * maxSpeed;
force = desiredVelocity - m_vehicle.velocity;
}
return force;
}
}
作者:
天国皇帝
时间:
2017-3-2 14:57
新人,求指教哈,没事来逛逛,
shown.png
(48.04 KB, 下载次数: 350)
2017-3-2 14:53 上传
点击文件名下载附件
作者:
may
时间:
2017-3-3 02:00
哈 不錯啊 謝謝
欢迎光临 纳金网 (http://rs.narkii.com/club/)
Powered by Discuz! X2.5