- Home /
How rotate a gameobject in Y axis using the mouse position at screen?
Answer by Casy10 · Sep 08, 2017 at 08:24 AM
Hello @Slaimi ! My guess would be that this is what you want :
using UnityEngine;
public class Rotator : MonoBehaviour
{
public float Sensitivity;
private Vector3 objectPositionToScreen;
private Vector3 mousePosition;
private void Start()
{
objectPositionToScreen = Camera.main.WorldToScreenPoint(transform.position);
}
void Update()
{
objectPositionToScreen = Camera.main.WorldToScreenPoint(transform.position);
if (Input.mousePosition.x > objectPositionToScreen.x)
transform.Rotate(0, Vector3.Magnitude(Input.mousePosition - objectPositionToScreen) * 0.01f * Sensitivity, 0);
else
transform.Rotate(0, Vector3.Magnitude(Input.mousePosition - objectPositionToScreen) * 0.01f * (-Sensitivity), 0);
}
}
This script needs to be attached on the object you want to rotate. Short explanation : The object will rotate to left if your mouse cursor will be on the left side of the object and it will rotate to right otherwise. You can use the Sensitivity to adjust the rotation speed in accordance to your needs. Have a good day !
You can add "-" before Sensitivity in the "if" section, and remove "-" before Sensitivity in the "else" section. That will cause the object to spin in reversed directions relative to y axis and this should be the appropiate effect.
@Casy10 No, this is not what I wanted. I want the GameObject to look at the mouse, not start spinning and the intensity increases when the mouse moves away.
Your answer
Follow this Question
Related Questions
Rotation help! 1 Answer
Help on rotating game object in C sharp 3 Answers
Locking onto enemies with the third person controller 2 Answers
Rotate Object 180º OnClick 3 Answers