- Home /
Question by
GameSlayerGS · Apr 02, 2013 at 08:30 AM ·
mouserotate
How do I rotate an object with the mouse?
My goal is to have an object get rotated when the mouse is moved in a direction, and to have it stay rotated until the mouse is moved in the opposite direction.
So far I have:
var xDeg = 0;
var yDeg = 0;
var currentX = 0;
var currentZ = 0;
function Update () { /*if(Input.GetMouseButton(0))*/
currentX = transform.position.x;
currentZ = transform.position.z;
xDeg = Input.GetAxis("Mouse X");
yDeg = Input.GetAxis("Mouse Y");
transform.rotation = /*Vector3(yDeg, xDeg, 0);*/ Quaternion.Euler(currentX + yDeg, 0, currentZ + xDeg * Time.deltaTime);
This successfully rotates it, but it rotates back if you stop moving the mouse. How can I get it to stay rotated?
Comment
Add to your x/yDef. When you stop moving Input.GetAxis is 0, therefore it goes back to 0 degree. Just add onto what you have moved thus far.
Ex. xDeg += Input.GetAxis("$$anonymous$$ouse X");
Best Answer
Answer by robertbu · Apr 02, 2013 at 03:49 PM
With relative motions you can use Transform.Rotate(). Quaternion.Euler() is an absolute rotation. @agocdrandin solution would work if you want to track the rotation.
var xDeg = 0;
var yDeg = 0;
var currentX = 0;
var currentZ = 0;
var speed = 10.0;
function Update () { /*if(Input.GetMouseButton(0))*/
currentX = transform.position.x;
currentZ = transform.position.z;
xDeg = -Input.GetAxis("Mouse X") * speed;
yDeg = Input.GetAxis("Mouse Y") * speed;
transform.Rotate(yDeg, xDeg, 0.0);
}