- Home /
Rotating object based off mouse input
Alright here's some background, I have a simple pickup object script that when the mouse is pressed and an object with a rigidbody is visible it will float the object in front of the player. Along with this I also have a rotate function so that when "r" is pressed the camera freezes position and the object will rotate based on mouse movement... well it should anyway. I have the rotation about the Y axis working its the x and z that are confusing me. Basically what I want is a way to see if the player is parallel to the z axis and rotate the object on the z and when the player is on the x axis rotate it on the x. Because it seems like the rotation is relative to the object itself and not the player. If there is someway to set the objects rotation relative to the player that would be awesome :D
Here's my humble code:
var rotationX:float = Input.GetAxis("Mouse X") sensitivityX; var rotationY:float = Input.GetAxis("Mouse Y") sensitivityY;
obj.transform.RotateAroundLocal(Vector3.down, rotationX); obj.transform.RotateAroundLocal(Vector3.forwards, rotationY);
Answer by TheLivingTree · Nov 22, 2013 at 12:45 AM
FIXED! here's my code for anyone interested:
function rotateObject()
{
//Gets the world vector space for cameras up vector
var relativeUp: Vector3 = mainCamera.transform.TransformDirection(Vector3.up);
//Gets world vector for space cameras right vector
var relativeRight: Vector3 = mainCamera.transform.TransformDirection(Vector3.right);
//Turns relativeUp vector from world to objects local space
var objectRelativeUp: Vector3 = obj.transform.InverseTransformDirection(relativeUp);
//Turns relativeRight vector from world to object local space
var objectRelaviveRight: Vector3 = obj.transform.InverseTransformDirection(relativeRight);
//Calculate rotation
rotateBy = Quaternion.AngleAxis(-Input.GetAxis("Mouse X") / obj.transform.localScale.x * sensitivityX, objectRelativeUp)
* Quaternion.AngleAxis(Input.GetAxis("Mouse Y") / obj.transform.localScale.x * sensitivityY, objectRelaviveRight);
//Finally rotate the object accordingly
obj.rigidbody.MoveRotation(obj.rigidbody.rotation * rotateBy);
}
I tweaked this script: http://answers.unity3d.com/questions/299126/how-to-rotate-relative-to-camera-angleposition.html
Thanks just what I spent hours looking for. I converted this to C# and it worked perfectly except the controls were completely inverted.... I'm sure I can fix that.
Your answer
Follow this Question
Related Questions
Rotating a camera that is already rotated on Z axis 0 Answers
How to look up and down with mouse 2 Answers
Flip over an object (smooth transition) 3 Answers
Player Rotation relitive to active camera 2 Answers
Make sphere rotate when controlled 7 Answers