查找Raycast Hit的Vector3

时间:2019-12-09 12:52:46

标签: c# unity3d

对于我的基于图块的游戏,我想为我的敌人创建一个视野。当玩家进入视野内时,敌人无法看穿障碍物并做出反应。

视线对象由一个立方体可视化,因为敌人只能在玩家位于同一轴上时发现他。

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChickenSightVer : MonoBehaviour
{
    PathFollower pathFollower;

    public GameObject player;
    public GameObject sightline;

    float rayLength = 20f;

    Ray myRay2;
    Ray myRay;

    bool onSameZAxis = false;


    void Start()
    {
        GameObject g = GameObject.Find("Path1");
        pathFollower = g.GetComponent<PathFollower>();
    }

    void Update()
    {
        if (RoughlyEqual(player.transform.position.x, transform.position.x) && pathFollower.hasCheckedXAxis == false)
        {
            onSameZAxis = true;
        }
        else { onSameZAxis = false; }

        //checks only when enemy stands still if the player is in sight
        if (onSameZAxis == true && pathFollower.standsStill == true && (PlayerInSight() == true || PlayerInSightother() == true))
        {
            pathFollower.sawPlayer = true;
            pathFollower.hasCheckedXAxis = true;

        }

        DrawSightline();

    }
    static bool RoughlyEqual(float a, float b)
    {
        float treshold = 0.2f; //how much roughly
        return (Mathf.Abs(a - b) < treshold);
    }

    void DrawSightline()
    {
        //Change the local Scaling at runtime
        //sightline.transform.localScale += new Vector3(0, 0, /*the Raycast hitpoint*/);

    }

    //checks if there is a wall between the player and the chicken
    bool PlayerInSight()
    {

        RaycastHit hit;

        myRay = new Ray(transform.position + new Vector3(0, 0.15f, 0), -transform.forward);


        Debug.DrawRay(myRay.origin, myRay.direction, Color.red);

        if (Physics.Raycast(myRay, out hit, rayLength))
        {
            if (hit.collider.tag == "Player")
            {
                return true;
            }
        }
        return false;
    }
    bool PlayerInSightother()
    {

        RaycastHit hit;

        myRay2 = new Ray(transform.position + new Vector3(0, 0.15f, 0), transform.forward);

        Debug.DrawRay(myRay2.origin, myRay2.direction, Color.red);

        if (Physics.Raycast(myRay2, out hit, rayLength))
        {
            if (hit.collider.tag == "Player")
            {
                return true;
            }
        }
        return false;
    }
}

您可以在代码中看到,我正在使用transform.localScale缩放视线立方体对象。现在,我只需要知道射线投射在哪个z位置撞上了障碍物。有没有办法找到这一点?

我非常感谢您的任何建议或想法!非常感谢你!

0 个答案:

没有答案