[벡터 내적] 플레이어와 몬스터가 있을때 몬스터가 앞에 있는지 뒤에 있는지 알아내는 방법

Unity3D 2016. 1. 5. 17:50
반응형

플레이어와 몬스터가 있을때 몬스터가 앞에 있는지 뒤에 있는지 알아내는 방법 





또는 이런상황이라면...?





다음 코드는 이렇다 


1. 몬스터가 플레이어 앞에 있는지 확인

2. 각도가 틀어졌는지 확인 



using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    public GameObject mon1;
    public GameObject mon2;

    private Transform trans1;
    private Transform trans2;

    // Use this for initialization
    void Start () {
        trans1 = mon1.transform;
        trans2 = mon2.transform;
    }
    
    // Update is called once per frame
    void Update () {
    
    }

    void OnGUI()
    {
        if (GUILayout.Button ("Check")) {
            Vector3 toTarget = (trans2.position - trans1.position).normalized;

            Debug.Log(toTarget);

            var dot = Vector3.Dot(toTargettrans1.forward); 

            Debug.Log(dot);

            var acos = Mathf.Acosdot );

            var angle = acos * 180 / Mathf.PI;

            Debug.Log(angle);
        }
    }
}






음 앞에 있군...


하지만 방향이 안맞으니 82도 틀어야 겠군 ... 


이렇게 되는것임.. 귀찮아서 설명은 대충 여기까지 







using UnityEngine;

using System.Collections;


public class DotTest : MonoBehaviour {


    public Transform target;

         

// Use this for initialization

void Start () {

}

// Update is called once per frame

void Update () {

        Vector3 direction = target.position - this.transform.position;

        float angle = Vector3.Angle(direction, this.transform.forward);


        Debug.Log(angle);


        if (angle < 30)

        {

            Debug.Log("In");

        }

        else

        {

            Debug.Log("Out");

        }


    }

}






반응형
: