我正在尝试以简单的方式编写AI脚本。 AI在它的前面,左边和右边做了一个光线投射。然后它以一种不包含“边界”元素的方式采用随机方向。
首先,我的Update()检查是否有时间计算新方向。如果是,则计算新方向,然后移动到该方向。
我正在使用以下代码移动:
Debug.DrawLine(transform.position, transform.position + transform.forward, Color.yellow);
Debug.DrawLine(transform.position, transform.position + transform.right, Color.yellow);
Debug.DrawLine(transform.position, transform.position - transform.right, Color.yellow);
//DEBUGS START AND END POSITION ARE CORRECT
var startTime;
if (Time.time > nextUpdate) {
Debug.Log("New check");
var dirWay = MoveDirection();
//if (dirWay == 0)
//rot = Quaternion.Euler(0, 0, 0);
if (dirWay == 1) {
rot = Quaternion.Euler(0, 90, 0);
}
if (dirWay == 2) {
rot = Quaternion.Euler(0, -90, 0);
}
if (dirWay == 3) { //backwards
rot = Quaternion.Euler(0, 180, 0);
}
nextUpdate = Time.time + walkTime; //for example, 2: Every 2 seconds an update
direction.y = 1;
direction.y = 1.5 - transform.position.y;
transform.rotation = transform.rotation * rot;
transform.position = transform.position + transform.forward + transform.forward;
//Plus 2 * transform.forward because it moves 2 places
}
函数MoveDirection通过光线投射检查障碍物。我的AI在正确的时间内移动了正确的距离,但穿过墙壁。这意味着我的光线投射是错误的。我正在使用以下代码:
var obstacles = ["Border", "Boundary", "BoundaryFlame"];
var frontAvailable = true;
var leftAvailable = true;
var rightAvailable = true;
var hitFront: RaycastHit;
if (Physics.Raycast(transform.position, transform.position + transform.forward, hitFront, 1.9)) {
for (var i = 0; i < obstacles.length; i++)
{
if (hitFront.collider.gameObject.name.IndexOf(obstacles[i]) > -1)
{
frontAvailable = false;
}
}
}
var hitLeft: RaycastHit;
if (Physics.Raycast(transform.position, transform.position - transform.right, hitLeft, 1.9)) {
for (var j = 0; j < obstacles.length; j++)
{
if (hitLeft.collider.gameObject.name.IndexOf(obstacles[j]) > -1)
{
leftAvailable = false;
}
}
}
var hitRight: RaycastHit;
if (Physics.Raycast(transform.position, transform.position + transform.right, hitRight, 1.9)) {
for (var k = 0; k < obstacles.length; k++)
{
if (hitRight.collider.gameObject.name.IndexOf(obstacles[k]) > -1)
{
rightAvailable = false;
}
}
}
所以,我是正确的当我想要检查AI前面的2个单位(从AI的角度看转换。转发,而不是全局视图!),我应该使用:Physics.Raycast(transform.position, transform.position + transform.forward, hitFront, 1.9)
?< / p>
答案 0 :(得分:0)
http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
所以,当我想检查AI前面的2个单位时,我是对的 (从人工智能的角度来看转换前进,而不是全局观点!), 我应该使用:Physics.Raycast(transform.position,transform.position + transform.forward,hitFront,1.9)?
你应该有Physics.Raycast(transform.position,transform.forward,hitFront,1.9);