I’m currently trying to figure how to make my camara rotate around the player controlled by mouse movement, the mouse x-axis rotating the camara AROUND the y axis, and the mouse y-axis rotating the camara ALONG the y axis. In other words: Classic 3rd person camara rotation. The problem is that I cannot figure where the camara must go (relative to the player) to be on the surface of an imaginary sphere around the player.
While trigometry in 2 dimentions is finally starting to make sense to me, I’m having problems wrapping my mind around this one, having 3 dimentions.
I’ve attached a picture I drew during my attempt to figure a way to calculate it, hopefully it will help making my point clear.
Make two game objects:
A GameObject “Pivot”, which is located at the position the camera should rotate around.
Another GameObject “Camera”, a child object of “Pivot”, with localPosition set to (0, 0, -distance_to_target).
To move the camera over the sphere, set the rotation of “Pivot” to (x_angle, y_angle, 0), where x_angle and y_angle are calculated from the mouse input.
Yes, I figured that was a possibility too, but then the problem is that I will need the very same calculation for fireing bullets. I may still be over complicating it, but this is the only (universal) solution I can come up with, exept I can’t calculate it.
With all the built-in vector and quaternion (rotation) functions available, it’s extremely rare that you would ever have to do any 3d calculations by hand in Unity.
If you want to fire a bullet directly along the same line as described by the line from the camera’s position to the player, you can simply subtract the player’s position from the camera’s position. This will give you a vector which describes the direction and distance from the camera to the player.
If your bullet is a physically moving object, you can then ‘normalize’ this vector, and multiply it by the speed with which you want the bullet to travel, and finally assign this as the bullet’s velocity.
If your bullet is a raycast (i.e. instantly travelling), you can use this vector as the raycast direction.
Thanks. Atleast it’s a solution. I’d still want to know how this is done the math way, in case i need it later (if nothing else, outside unity) but I guess I’ll have to go to a math forum or something simmilar then.
Vector3 target_position; // the position of the target we're following
Vector3 distance_to_target = new Vector3(0, 0, -distance); // distance the camera should be from target
Matrix4x4 t = Matrix4x4.TRS(target_position, Quaternion.Euler(x_angle, y_angle, 0), Vector3.one);
Vector3 camera_position = t.MultiplyPoint(distance_to_target);
Oh cool!
Deffently not what i’d expected, true, but I just did a quick search and there seems to be plenty of matrix4x4 classes for C++, which was my other concert.
So thanks a lot!
Chris
EDIT:
Just wanted everyone who reads this topic later on to know that this actually worked perfectly!