- Home /
Having trouble finding angle of the object.
I've been trying to get this code to work for an object to draw a line to the player based on the players current location. This script is going to be used for the enemyAi to follow the player so I'm going to use dir (which is the angle that the object is looking at) and then use the translate the object by using the Sin(dir) spd; and the Cos(dir) spd;
My Code:
dir =Mathf.Deg2Rad * Vector3.Angle(player.transform.position - transform.position,Vector3.forward);
Debug.DrawRay(transform.position,new Vector3(Mathf.Sin(dir),0,Mathf.Cos(dir))*sightRange);
//To move the enemy object
amountToMove.x = Mathf.Sin(dir)*spd*Time.deltaTime;
amountToMove.z = Mathf.Cos(dir)*spd*Time.deltaTime;
But for some reason it either doesn't work and points in a different direction or only works at certain spots.
Any reasons why this is happening?
What are you trying to find the angle of in comparison to what position or direction?
I have one object and the player. What I need to do is find the angle between the object and the player
To get the angle you need two vectors, the distance between the two items is one vector. What do you want the other to be? the direction the player is facing?
Also, do you actually want an angle, or do you want the vector/distance between the two?
Answer by robertbu · Dec 05, 2013 at 01:39 AM
Angles in 3D space take more thought than angles in 2D space. You have to ask, "angle relative to what?" In addition angles you get back are unsigned. You have to provide a reference and some additional code to get a signed angle.
Typically the kind of problem you are outlining (drawing a line between points), is handled by vectors. If you outline how you are drawing lines, then it is likely we can give you a simple solution that avoid complicated angle calculations.
Given what I can see of your code, if you need to plow ahead with angles, take a look at Mathf.Atan2().
Your answer
Follow this Question
Related Questions
Changing position of a RayCast 1 Answer
Detect if raycast hit the specific object. 1 Answer
Physics.Raycast intermittently stops working 1 Answer
Raycast on touch 3 Answers
Problem with raycasting when checking neighbouring objects? 0 Answers