Unity3D射線檢測牆面前停止移動

public class test : MonoBehaviour
{
    public GameObject Self;
    public GameObject Fake;
    public GameObject Target;
    public float width;

    public float rayAngle;
    public float rayDirectValue;
    public float realGetLenght;
    public Vector3 rayVector;
    public Vector3 realGetVector;

    public float offerAngle;
    public float offerSin;
    public float offerCos;
    public float offerXValue;
    public float offerZValue;

    void Start()
    {
        width = Self.GetComponent<CapsuleCollider>().radius * Self.transform.localScale.x;
    }

    void Update()
    {
        Vector3 wantPos = Target.transform.position;
        Vector3 realGetPos = Vector3.zero;
        RaycastHit raycastHit = new RaycastHit();
        Ray wallCheck = new Ray(Self.transform.position, Target.transform.position - Self.transform.position);
        if (Physics.Raycast(wallCheck, out raycastHit, Vector3.Distance(Target.transform.position, Self.transform.position) + 8, 1 << LayerMask.NameToLayer("Ground")))
        {
            rayAngle = Vector3.Angle(Self.transform.position - Target.transform.position, raycastHit.normal);
            rayDirectValue = width / Mathf.Cos(Mathf.PI / 180 * rayAngle);
            rayVector = raycastHit.point - Self.transform.position;
            realGetLenght = rayVector.magnitude - rayDirectValue;           
            realGetVector = rayVector.normalized * realGetLenght;
            realGetPos = new Vector3(
                    Self.transform.position.x + realGetVector.x,
                    Self.transform.position.y,
                    Self.transform.position.z + realGetVector.z);
        }
        else
            realGetPos = wantPos;
        
        Fake.transform.position = realGetPos;
        Debug.DrawLine(Self.transform.position, wantPos, Color.red);
        Debug.DrawLine(Self.transform.position, realGetPos, Color.blue);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章