我正在制作一个AI蜘蛛,当它离墙太近时会停止。然而,使用我下面的代码,它只能在面对迷宫的北墙(全局前方)时成功执行Idle()。
我使用的是Unity3D 4.6。
这是我的代码:
using UnityEngine;using System.Collections;public class Spider : MonoBehaviour { public float movementSpeed, rotationSpeed; //在实例化后由游戏管理器调用 public void SetLocation (MazeCell cell) { transform.localPosition = new Vector3( cell.transform.localPosition.x, 5f, cell.transform.localPosition.z ); float startingRotation = Mathf.RoundToInt(Random.Range(-0.5f,3.49999f)); transform.rotation = Quaternion.Euler(0,startingRotation * 90,0); } void Update() { if (Physics.Raycast(transform.position, Vector3.down, 0.5f)) { if (!Physics.Raycast(transform.position, transform.forward, 2)) { Walk(); } else { Idle (); } } } private void Idle() { animation.Play("idle"); } private void Walk() { transform.Translate(transform.forward * movementSpeed * Time.deltaTime); animation.Play("walk"); } }
编辑:
Debug.Log()
调用
新代码
回答:
我已经回答了自己的问题(但我必须感谢@***帮助我看到了这些可能性并可靠地协助我)。事实上,问题是一系列问题的集合。
最重要的问题是射线投射的起点太低。这导致地板被视为墙壁,使蜘蛛无法行走。这也阻止了向下的Raycast
正常工作。
然而,最终需要结合使用transform.forward
和Vector3.forward
来获得所需的功能。这是最终的代码:
using UnityEngine;using System.Collections;public class Spider : MonoBehaviour {public float movementSpeed, rotationSpeed;public void SetLocation (MazeCell cell) { transform.localPosition = new Vector3( cell.transform.localPosition.x, 5f, cell.transform.localPosition.z ); float startingRotation = Mathf.RoundToInt(Random.Range(-0.5f,3.49999f)); transform.rotation = Quaternion.Euler(0,startingRotation * 90,0);} void Update() { Debug.Log ("updating"); if (Physics.Raycast( new Vector3(transform.position.x, transform.position.y + 0.25f, transform.position.z), Vector3.down, 0.5f)) { Debug.Log("downraycheck passed"); if (!Physics.Raycast( new Vector3(transform.position.x, transform.position.y + 0.25f, transform.position.z), transform.forward, 2)) { Debug.Log("forwardraycheck passed"); Walk(); } else { Debug.Log("forwardraycheck failed"); Idle (); } }}private void Idle() { Debug.Log("idling"); animation.Play("idle");}private void Walk() { Debug.Log("walking"); transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime); animation.Play("walk");}}