我正在使用一些基本的避障算法来避开障碍物,但是我遇到了左右传感器的问题。当两者都活跃时。他们将取消他们的旋转而根本不旋转。通过前传感器找出hit.normals也有点麻烦。
ray = new Ray(transform.position + Vector3.up, transform.forward);
Vector3 posInicial = transform.position;
if (Physics.Raycast(ray, out hit, 55f)) // Front sensor
{
if (hit.collider.tag == ("Pick Up")) // If robot detects pick up, it goes towards it
{
Debug.DrawLine(ray.origin, hit.point, Color.red);
transform.position = Vector3.MoveTowards(transform.position, hit.point, Time.deltaTime * speed);
}
else
{
transform.Rotate(0, -80 * Time.deltaTime, 0); // Rotate if front sensor doesn't detect pick up
Debug.DrawLine(ray.origin, hit.point, Color.blue);
}
}
else
{
transform.position += transform.forward * speed * Time.deltaTime; // Go forward
Debug.DrawLine(ray.origin, hit.point, Color.white);
}
if (Physics.Raycast(posInicial, Quaternion.AngleAxis(45f, transform.up) * transform.forward, out hit2, 20f))
{
transform.Rotate(0, -80 * Time.deltaTime, 0); // Rotate left if right detected
Debug.DrawLine(posInicial, hit2.point, Color.yellow);
}
if (Physics.Raycast(posInicial, Quaternion.AngleAxis(-45f, transform.up) * transform.forward, out hit3, 20f))
{
transform.Rotate(0, 80 * Time.deltaTime, 0); // rotate right if detected left
Debug.DrawLine(posInicial, hit3.point, Color.cyan);
}
}
答案 0 :(得分:2)
我不确定你为什么要自己实现这个。如果是因为你对算法感兴趣并且你想在将来将它推断到真实世界,那就没关系。
但是为了以防万一,在Unity中已经有一个名为NavMesh的东西,它基本上为游戏提供了一个AI,例如敌人,它们可以识别障碍物,以便在场景中从一个点移动到另一个点时避开它们。 / p>
将场景烘焙后,您可以将导航网格添加到游戏对象:
public class EnemyMovement : MonoBehaviour
{
NavMeshAgent nav;
function Awake ()
{
nav = GetComponent(NavMeshAgent);
}
//So here it will be chasing the player
function Update ()
{
nav.SetDestination (player.position);
}
}
进行操作