c# - 如何在 Ray 的帮助下定位 GameObject?
问题描述
对于我的基于网格的游戏,我希望敌人拥有玩家可见的视线。敌人只能朝一个方向(上、下、左或右)看,一旦设定,他们就不会改变那个方向。
敌人无法透过障碍物或其他敌人,这就是我设置 Raycast 的原因。此 Raycast 检测玩家是否在与敌人方向一致的直线上。
这是我的 EnemySight 脚本:
PathFollower pathFollower;
public GameObject sightline;
public GameObject player;
float rayLength = 20f;
bool onSameZAxis = false;
Ray myRay;
RaycastHit hit;
void Start()
{
GameObject g = GameObject.Find("Path");
pathFollower = g.GetComponent<PathFollower>();
}
void Update()
{
DrawRay();
if (player.transform.position.z.Equals(transform.position.z) && pathFollower.hasCheckedAxis == false)
{
onSameZAxis = true;
}
else { onSameZAxis = false; }
//checks only when enemy stands still if the player is in sight and on same axis
if (onSameZAxis == true && pathFollower.standsStill == true && PlayerInSight() == true)
{
Debug.Log("spotted");
pathFollower.sawPlayer = true;
pathFollower.hasCheckedAxis = true;
//onSameZAxis = false;
//Debug.Log("In the If-Loop");
}
}
//checks if there is a wall between the player and the enemy
bool PlayerInSight()
{
myRay = new Ray(transform.position + new Vector3(0, 0.15f, 0), -transform.right);
Debug.DrawRay(myRay.origin, myRay.direction, Color.red);
if (Physics.Raycast(myRay, out hit, rayLength))
{
if (hit.collider.tag == "Player")
{
return true;
}
}
return false;
}
void DrawRay()
{
//Moves the Sightline Object.
}
}
我已将 Sightline GameObject 设为相应敌人的子对象,因此它与敌人一起移动。问题是它会穿过障碍物和敌人,尽管那时不会检测到玩家。
我正在考虑将我的 Sightline GameObject 的轴心点移动到 Raycast 的 Vector 3 命中,但我不知道这如何工作。
我很高兴有任何建议或解决方案,在此先感谢您!
解决方案
推荐阅读
- sql - 使用嵌套从 JSON 中提取值
- ssis - 将项目级别参数分配给 BIMLScript 中的变量
- .htaccess - 如何禁用 .htaccess 的执行并输出它的内容
- vuejs2 - Vuex 状态未完全更新兄弟控件
- react-native - 在 JSX javascript 表达式中使用 Platform.select 时缺少组件:例如 return (<>{Platform.select({})});
- ruby-on-rails - 如何在 Ruby on Rails 中显示 has_many 组件
- wordpress - 使用联系表 7 更新用户元数据
- javascript - 从日期中找出月份的周数
- unity3d - 统一光子视图
- c# - 从对象(类)c#创建xml文件