- Home /
Find angle between two gameobjects?
I know this has been asked a lot, but the only answer I see is Vector3.Angle, I don't want to use that. I'm making a graphing calculator, I have everything working fine, except I can't find what angle the graphed line is. I'm using this function to try to calculate it:
void CalculateAngle(GameObject x, GameObject y) {
float xDis = y.transform.position.x - x.transform.position.x;
float yDis = y.transform.position.y - x.transform.position.y;
Debug.Log(xDis + " : " + yDis);
}
The gameobects that is calls for are the first two plotted points of a line(my calculator only supports straight lines for now), I want to find the angle between those them, then spawn a long, thin cube at their position at that angle to draw the line. I thought I was onto something with that code, but I have no idea what it was. I really need some help with this, I'm not too good with math and this is hurting my brain.
Also, incase it matters, I'm not using the z axis.
Do you actually have to do the math or are you just wanting to display? If just for display you could simply use a LineRenderer
drawn from the first position to the second.
If anybody wants the full code: http://pastebin.com/9raT38d6
@$$anonymous$$cAden I'm just wanting a line connecting the points on the graph.
You could use Unity's line renderer?
http://docs.unity3d.com/Documentation/Components/class-LineRenderer.html
Answer by robertbu · Apr 01, 2014 at 08:00 PM
To begin with, as @McAden says, you can just draw a line using the LineRenderer class. More information on drawing lines here:
Plus if you are willing to spend some $, Vectrosity makes your task of drawing a line for your calculator trivial.
If you really want the angle. You can use Mathf.Atan2(). I really suggest a better name for your two game objects, but you can calculate the angle like:
Vector3 dir = y.position - x.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
As for placing a quad between two points, you can do it this way:
var dir = x.position - y.position;
var mid = (dir) / 2.0 + x.position;
quad.position = mid;
quad.rotation = Quaternion.FromToRotation(Vector3.right, dir);
quad.localScale.x = dir.magnitude * factor;
Where 'quad' is the transform of a Quad game object you are placing and rotating to match the two points. 'factor' will be 1.0 for a Quad. If you were placing some other object (cylinders work well with spheres at the joints), you'll need to adjust 'factor'.