- Home /
Question by
MattDahEpic · Jul 30, 2017 at 02:02 AM ·
raycastingfrustrum
Unable to place gameobject at edge of screen
I'm trying to make an arrow that points towards an objective offscreen, but have been running into placement problems. I have the rotation figured out, the objects point towards their intended targets just fine, but they get places way off screen. They should be right near the edge.
This game is in 2D.
My current code is: (currentDisplays is a dictionary with Transform as the value)
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(Camera.main); //edges of viewport
Ray r = new Ray(Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, -10)), p.transform.position - Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, -10))); //ray from center of screen to point
float distToEdge;
Vector3 displayPos = new Vector3(1000,1000,1000);
//where does the ray collide with the edges of the viewport?
if (planes[0].Raycast(r,out distToEdge)) { //left side of screen
displayPos = r.GetPoint(distToEdge - 0.75f);
}
if (planes[1].Raycast(r,out distToEdge)) { //right side of screen
displayPos = r.GetPoint(distToEdge - 0.75f);
}
if (planes[2].Raycast(r,out distToEdge)) { //bottom side of screen
displayPos = r.GetPoint(distToEdge - 0.75f);
}
if (planes[3].Raycast(r,out distToEdge)) { //top side of screen
displayPos = r.GetPoint(distToEdge - 0.75f);
}
currentDisplays[p].position = displayPos;
Vector2 targetLook = p.transform.position - currentDisplays[p].transform.position;
var angle = Mathf.Atan2(targetLook.y, targetLook.x) * Mathf.Rad2Deg;
angle -= 90f;
currentDisplays[p].rotation = Quaternion.AngleAxis(angle, Vector3.forward);
Thank you for your help!
Comment