Rotate an object towards mouse cursor on click Help!

Hi guys, This is killing me for hours…
I want simply to rotate an object towards the mouse cursor when I click. The scripts works, but in its current state when I click, the object rotates just a little bit. I have to click many times to get the object to rotate in the right position.

When I use just GetMouseButton, I can hold the mouse button and the object follow the mouse fine, but I want to rotate the object with just one click. How can I achive that?

Its in JavaScript

Thank you in Advance! :slight_smile:

function Update () {
    if (Input.GetMouseButtonDown(0)) {
     
    Turn();
     
    }
    }
     
    function Turn () {
     
    var newPlane = new Plane(Vector3.up, transform.position);
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hitDistance = 0.0;
     
     
    newPlane.Raycast(ray, hitDistance);
    var targetPoint = ray.GetPoint(hitDistance);
     
     
    var newRot = Quaternion.LookRotation(transform.position - targetPoint, Vector3.up);
    transform.rotation = Quaternion.Slerp(transform.rotation, newRot, Time.deltaTime * 2);
     
    }

You’re turning needs to be updated but your click is too short time wise.

Using a bool that stays true till looking at your mouse position should do the trick.

ofc you could use a coroutine / while loop till the condition is met.

Good thinking man, I haven’t thought of that. I don’t have Unity in front of me right now, but I will test it tonight :slight_smile:

This should do the trick :

function Update ()
{
   	if (Input.GetMouseButton(0))
		  Turn();
}

function Turn ()
{
    var mousePos = Input.mousePosition;
    mousePos.z = 10.0f;
    var lookPosition : Vector3 = Camera.main.ScreenToWorldPoint(mousePos);
    lookPosition = lookPosition - transform.position;
    var rotAngle : float = Mathf.Atan2(lookPosition.y, lookPosition.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.AngleAxis(rotAngle, Vector3.up);
}

One click will instantly rotate the gameobject (dragging the mouse while pressing the left button will also work).

Thanks for the response PMerlaud
I tried your script, but the object immediately snaps on the cursor, which I can achieve with transform.LookAt. I want to make a smooth rotation from one position with to another.

As Black Mantis suggested I need a condition to check if the Vector of the object that rotates, points at the mouse cursor. But how do I do that?
Does anybody know?
Thank you

Anybody?