We often encounter this problem in the game. For example, if the enemy encounters the protagonist, he will rotate over him. Or judge the protagonist on the left or right, etc.
:
The cross of a vector, a, B, gets a C vector perpendicular to them, and we can judge a region of the enemy's four regions by the value above.
The implementation of the Code:
usingUnityengine;usingSystem.Collections; Public classTest:monobehaviour { PublicTransform A; PublicTransform B; PublicTextmesh text; PublicTextmesh Oneresult; PublicTextmesh Tworesult; Public floatdistance; Private floatdot; Public voidUpdate () {//b in front of a, A is the protagonist, B is the enemyVector3 Toother = a.transform.position-b.position; //gets the Y to judge the enemy on the left and right side of the characterVector3 chaCheng1 =Vector3.cross (A.forward, Toother); Vector3 chaCheng2=Vector3.cross (A.right, Toother); Oneresult.text=chacheng1.tostring (); Tworesult.text=chacheng2.tostring (); Debug.Log ("first-time value:"+chaCheng1); //Gets the Y can judge the enemy in front of the character and behindDebug.Log ("second time value:"+chaCheng2); if(Chacheng1.y >0&& chacheng2.y >0) {Text.text="Location: Upper left"; } if(Chacheng1.y <0&& Chacheng2.y <0) {Text.text="location: Lower right"; } if(Chacheng1.y >0&& Chacheng2.y <0) {Text.text="location: Lower left"; } if(Chacheng1.y <0&& chacheng2.y >0) {Text.text="Location: Upper right"; } } }
Project: Http://yunpan.cn/cdYkG48mxIGGD access password 54c3
Cross-multiplication realizes the position judgment of the character and the enemy (upper left, bottom left, upper right, bottom right)