Hola!
I’m instantiating a new GameObject from a prefab, which is most often going to be a attack laser/beam/etc. So, I want it to be drawn between two objects (which I call here origin and target).
I figure that beam object should be positioned in a center point between origin and target, and that part works well… and I can also calculate scale based on the distance between the two:
// get the middle point between the objects
Vector3 center = Vector3.Lerp(origin.transform.position, target.transform.position, 0.5F);
Part where I’m struggling with is rotating the beam object so it looks like it’s connecting the origin and target. It’s a 3d space, but angle is 2d since Y plane is fixed.
Here’s the code I’ve had that failed miserably:
// this angle is always too small, while it should go from 0 to 360 or such
float angle = Vector2.Angle(new Vector2(origin.transform.position.x, origin.transform.position.z), new Vector2(target.transform.position.x, target.transform.position.z));
I’ve also tried snippets with Quaternion.FromToRotation, Vector3.Cross, .LookAt, and very much anything I could google with finding angle between two objects.
At this point I’m about to go back to basics and calculate angle myself between two points, just like we did in college, but I hope there’s more elegant solution out there, especially with all built-in Unity functions.