- Home /
Issues calculating angle in 2D
I have read 100 answer's on this but can not get it to work. I am trying to match the angle of a lineRenderer I must be feeding the wrong coordinates into the function but I can't figure out what its supposed to be. I have tried, transform.position, transform.localPosition, rectTransform.localPosition, rectTransform.anchored position. lineRenderer.GetPosition 1 and 0, converting those to world and screen coordinates. Nothing will give me the right angle. Using Camera.main.ScreentoWorld with the recttransform gets close but its still off by several degrees. I am at a total loss here.
I know the GrappleComponent.PivotPoint is correct as the line is drawn to where I tap and the web game object is positioned where I tapped. Its just the angle that is the problem.
Right now I am using the functions found in http://answers.unity3d.com/questions/317648/angle-between-two-vectors.html as there are known issues with Vector2.Angle. Though Vector2, or Vector3 don't get close to working either.
private void SwipedDown(CustomEvent customEvent)
{
Debug.Log("Swiped down event received");
if (Attached)
{
try
{
GameObject platForm;
RaycastHit2D hit = Physics2D.Raycast(transform.position, -transform.up, 5);
if(hit)
{
platForm = hit.collider.gameObject;
}
else
{
Debug.LogError("Not on a platform to attach web to");
return;
}
Attached = false;
GameObject web = Instantiate((GameObject)Resources.Load("Prefabs/Web"), platForm.transform);
web.transform.localScale = new Vector3(1, 1, 1);
web.transform.position = GrappleComponent.PivotPoint;
float length = Vector2.Distance(transform.localPosition, web.transform.position);
web.GetComponent<RectTransform>().sizeDelta = new Vector2(10, length);
web.GetComponent<BoxCollider2D>().size = web.GetComponent<RectTransform>().sizeDelta;
web.GetComponent<BoxCollider2D>().offset = new Vector2(0, -web.GetComponent<RectTransform>().rect.height / 2);
web.GetComponent<LineRenderer>().SetPosition(0, GrappleComponent.Rope.GetPosition(0));
web.GetComponent<LineRenderer>().SetPosition(1, GrappleComponent.Rope.GetPosition(1));
float angle = AngleInDeg((Vector2)web.transform.position, (Vector2)transform.position);
web.transform.rotation = Quaternion.Euler(0, 0, angle );
GrappleComponent.ReleaseRope();
}
catch(Exception exception)
{
Debug.LogError(exception.Message);
}
}
else
{
}
}
//This returns the angle in radians
public static float AngleInRad(Vector2 vec1, Vector2 vec2)
{
return Mathf.Atan2(vec2.y - vec1.y, vec2.x - vec1.x);
}
//This returns the angle in degrees
public static float AngleInDeg(Vector2 vec1, Vector2 vec2)
{
return AngleInRad(vec1, vec2) * 180 / Mathf.PI;
}