Object rotations based on mouse movement is a common feature in 3D games and simulations. It provides an interactive way to control objects and navigate scenes. In Unity, this functionality can be achieved using C# scripts.
You can add the sample C# script to the GameObject as a component to rotate it based on your mouse movements along the horizontal and vertical directions.
Note:
Since there are only two axes of movement with the mouse (
and ), adding rotation along the axis gets a little tricky. One idea is to combine both the
and rotation into a random axis rotation.
Given below is a sample C# script that enables an object to rotate based on the mouse movement along the
using System.Collections;using System.Collections.Generic;using UnityEngine;public class MouseRotation : MonoBehaviour{public float sensitivity = 0.1f;public void Update(){float rotationX = Input.GetAxis("Mouse X") * sensitivity;float rotationY = Input.GetAxis("Mouse Y") * sensitivity;transform.Rotate(Vector3.up, -rotationX, Space.World);transform.Rotate(Vector3.right, rotationY, Space.World);}}
Lines 1–3: These lines import all the required namespaces.
Line 5: A class is declared named MouseRotation
. It inherits methods from the class MonoBehaviour
, a base class in Unity for scripts attached to the specific GameObjects.
Line 7: It declares a public variable named sensitivity to control the speed of the rotation. You can adjust the speed in the inspector window.
Line 9: The Update
method is declared here which is called once per frame.
Lines 11–12: These lines reads the horizontal and vertical mouse movement using Input.GetAxis
method. It then multiplies it by the sensitivity
value to get the rotationX
and rotationY
.
Lines 14–15: Transform.Rotate
method applies rotation to the GameObject. The object is rotated around the global up
axis (Vector3.up
) by an amount of -rotationX
degrees and right
axis by an amount of rotationY
degrees. The rotations are performed in the world space, which means that they are not affected by the local rotation of the GameObjects.
float rotationZ = -(rotationX + rotationY) * sensitivity;transform.Rotate(Vector3.forward, rotationZ, Space.World);
Here,
Line 1: It calculates the combined mouse movement as sensitivity
to control the speed of the rotation.
Line 2: It applies the forward
rotation to the GameObject by an amount of rotationZ
degree. The rotation is performed in the world space, which means that it is not affected by the local rotations of the GameObjects.
The sample project demonstrates the rotation of the object based on the mouse movements (along horizontal and vertical direction).
The speed of rotation is set to 4.0
.
import React from 'react'; require('./style.css'); import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );
Free Resources