Evening.
What I want to do is have the player rotate to face the direction of the camera if I press a certain button. The only issue is that, having tried this sort of thing before, it NEVER works. Ever. It either only goes halfway to the target rotation, or doesn’t do anything at all.
I’ve tried it with all of the following possibilities both under an if/input statement in Update, and in a separate coroutine called in Update:
-gameObject.rotation.y = target.rotation.y;
-gameObject.localRotation.y = target.localRotation.y;
-gameObject.eulerAngles.y = target.eulerAngles.y;
-gameObject.rotation = targetRotation (A variable that’s storing the target’s rotation)
-gameObject.rotation = Quaternion.Euler(0, targetRotation, 0);
-gameObject.localRotation = Quaternion.Euler(0, targetRotation, 0);
None of these have worked and, as you may have guessed, I’m a bit miffed. How on earth can I do this?
Create a new scene, attach the below script to an empty gameObject or the camera (it doesn’t matter, this is just a test). Hit play then move the mouse horizontally. The cube that is created follows the Y rotation of the camera.
This is where the magic happens :
myCube.rotation = Quaternion.Euler( myCube.rotation.eulerAngles.x, myCamera.rotation.eulerAngles.y, myCube.rotation.eulerAngles.z );
Sets the rotation using Euler angles. The whole rotation is constructed using the eulerAngles of the cube X and Z, then the eulerAngles Y of the camera. When the whole rotation is built with Euler angles, that rotation is given as a Euler to the cube rotation.
#pragma strict
var myCube : Transform;
var myCamera : Transform;
function Start()
{
// cache camera transform
myCamera = Camera.main.transform;
// create cube to rotate
var cube : GameObject = GameObject.CreatePrimitive( PrimitiveType.Cube );
myCube = cube.transform;
myCube.position = myCamera.position + ( Vector3.forward * 5.0 );
}
function Update()
{
RotateCam();
RotateCube();
}
function RotateCam()
{
myCamera.rotation *= Quaternion.Euler( 0, Input.GetAxis ("Mouse X"), 0 );
}
function RotateCube()
{
myCube.rotation = Quaternion.Euler( myCube.rotation.eulerAngles.x, myCamera.rotation.eulerAngles.y, myCube.rotation.eulerAngles.z );
}
you want to look the direction of the camera as in at the camera or the way the camera is facing
player.transform.lookat(camera)
to look at the camera
player.transform.forward = camera.transform.forward
would PROBABLY get you to look in the direction the camera is
mark if answered let me know if you need more help
Thanks for the responses, guys. Since neither of you said anything about it being a common issue, I figured that there must be something else interfering with the commands. I tried some things out, and it seems that having MouseLook attached to the character prevented it from working correctly.
Thanks for helping out, guys! I’ll give you thumbs up once I figure out why the site won’t let me do so.