- Home /
Rotate an object based on Camera's axis
Hi So I have an assignment for class and I am having some trouble with this one part.
Basically I have an object that needs to rotate based on the view that the main camera sees it.
For example, The object is at 0,0,0. and such it's transform.forward is 0,0,1. But the camera's transform.forward is 0.5,0,0. I need the object to act as if it's transform.forward is 0.5,0,0.
Another example is that the object needs to jump in the direction of the camera. If the camera is sideways in the world, the player needs to jump sideways as well.
Any help would be appreciated
Answer by UnityVeris · Dec 04, 2017 at 05:43 AM
You say the object needs to rotate based on the cameras axis', but you've described a translation (jumping).
I'm going to assume you mean translation:
// Get the position of the GameObject you want to move
// I'm assuming it's a player (playerObject)
Vector3 newPos = playerObject.transform.position;
// Modify the new position however you like
// In this case we are modifying it with respect to the
// camera (cameraObject) rotation
newPos += (cameraObject.transform.right * (float)speed);
// Set the player in the new location
playerObject.transform.position = newPos;
You can use the following to get different directions:
transform.up = objects local +Y axis.
-transform.up = objects local -Y axis.
transform.right = objects local +X axis.
-transform.right = objects local -X axis.
transform.forward = objects local +Z axis.
-transform.forward = objects local -Z axis.
Answer by KravenArk · Dec 06, 2017 at 06:47 AM
That actually helped a lot. What I ended up doing was recording the forward direction of the camera and using that to direct the player when they rotate, move or jump. Essentially the idea is that the camera moves around the player but wherever the camera's forward is, the player will move that way. So the player doesnt have to adjust their motion based on the camera's location
Glad that helped, sorry I wasn't entirely sure how to interpret parts of the question.
There are a bunch of other ways to go about it, like having an invisible dummy object that you move around to figure out new values, or parenting objects and then adjusting local coordinates, but I find just getting and setting like that is easy to think about, reads well and suits most situations.
Your answer
Follow this Question
Related Questions
Rotate object based on another rotation above a certain threshhold 1 Answer
gameobject stops moving correctly when rotating 1 Answer
Smooth rotation about global axis instead of local axis. 1 Answer
Rotating enemy object to face the player when moving 2 Answers
I need Some Info About Rotation And Pvot 0 Answers