- Home /
Issue rotating objects with input from the mouse wheel
Hey there everyone, first time poster here.
So, I've got a c# script that is supposed to get input from the mouse wheel and then use that input to rotate a game object.
I can get input from the mouse wheel no problem, but as soon as I scroll the wheel the game object locks into an upright position and will jiggle around a little bit if I move the mouse wheel, but won't rotate like it should. Been banging my head all day trying to figure this out, so any assistance with this would be greatly appreciated. The script is pretty short, so I'll post the thing in its entirety here.
using UnityEngine;
using System.Collections;
public class Adjust_Sights : MonoBehaviour {
private float rot; //stores the rotation of the mouse wheel
private float speed; //multiplier for the mouse wheel input
private Quaternion storePos; //stores the rotation of the attached gameObject
// Use this for initialization
void Start () {
speed = 10.0f;
}
// Update is called once per frame
void Update () {
rot = Input.GetAxis("Mouse ScrollWheel") * speed * Time.deltaTime; //gets the mouse wheel input and stores it in ro
storePos = gameObject.transform.rotation; //keeps storePos up to date
if (rot != 0)
{
transform.eulerAngles = new Vector3(storePos.x, storePos.y, rot); //Doest the actual rotation of the object
}
}
}
Answer by maccabbe · Jul 16, 2015 at 07:12 AM
First, gameObject.transform.rotation returns a Quaternion (4 parts w, x, y, z). You probably want transform.eulerAngles which is a Vector3 (3 parts x, y, z) for storePos.
Second, you probably don't want the z rotation to be directly proportional to how much the mousewheel has moved but rather added onto the current z rotation.
Try
using UnityEngine;
using System.Collections;
public class Adjust_Sights : MonoBehaviour {
private float rot; //stores the rotation of the mouse wheel
private float speed; //multiplier for the mouse wheel input
private Vector3 storePos; //stores the rotation of the attached gameObject
// Use this for initialization
void Start () {
speed = 10.0f;
storePos = gameObject.transform.eulerAngles; //keeps storePos up to date
}
// Update is called once per frame
void Update () {
rot = Input.GetAxis("Mouse ScrollWheel") * speed * Time.deltaTime;
if (rot != 0)
{
storePos= new Vector3(storePos.x, storePos.y, storePos.z+rot);
transform.eulerAngles = storePos;
}
}
}
This worked perfectly, thank you! I just had to adjust speed and put the storePos = gameObject... back into update, since the script is attached to an object that will be walking around and it will need to be kept in the same x and y position in relation to its parented object. Again, thank you so much!