- Home /
Angle to position on a cube
Hi!
I want to calculate a position on the surface of a cube, only using an angle from the center of the cube, in other words, the point a ray intersects with the cube if the ray leaves from the center of the cube.
Is there any easy way of calculating this with a quaterion, matrix or euler angle?
void f(GameObject cube, Quaternion a) {
Vector3 intersectPoint;
/* calc */
return intersectPoint;
}
Thanks in advance!
Answer by veclock · Aug 19, 2012 at 11:16 PM
Think I found a solution:
Vector3 p = Random.onUnitSphere*cube.transform.localScale.magnitude; if (p.x > cube.transform.localScale.x*0.5f) { p.x = cube.transform.localScale.x*0.5f; } else if (p.x < -cube.transform.localScale.x*0.5f) { p.x = -cube.transform.localScale.x*0.5f; } if (p.y > cube.transform.localScale.y*0.5f) { p.y = cube.transform.localScale.y*0.5f; } else if (p.y < -cube.transform.localScale.y*0.5f) { p.y = -cube.transform.localScale.y*0.5f; }
if (p.z > cube.transform.localScale.z*0.5f) { p.z = cube.transform.localScale.z*0.5f; } else if (p.z < -cube.transform.localScale.z*0.5f) { p.z = -cube.transform.localScale.z*0.5f; } If there's a better way, please share!
Answer by aldonaletto · Aug 20, 2012 at 01:17 AM
That's a good solution, but will fail when the cube is rotated and/or not centered at (0,0,0). Additionally, each time you read cube.transform.localScale, Unity makes calls to the internal functions getTransform and getLocalScale, what wastes time.
Your algorithm may be changed to solve all these problems:
// get a random point p in the surface of the sphere // that encapsulates a cube with dimensions 1x1x1: Vector3 p = Random.onUnitSphere; // flatten the point on the 1x1x1 cube surface: p.x = Mathf.Clamp(p.x, -0.5f, 0.5f); p.y = Mathf.Clamp(p.y, -0.5f, 0.5f); p.z = Mathf.Clamp(p.z, -0.5f, 0.5f); // convert the point to the actual cube surface, according // to its position, rotation and scale: p = cube.transform.TransformPoint(p);The first four instructions actually create a kind of Random.onUnitCube function, and the last one transform it to the actual cube surface.
Your answer
![](https://koobas.hobune.stream/wayback/20220613075907im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how to find direction between two points 2 Answers
max size of a cube at irregular angles 2 Answers
Find out x at y 0 Answers