- Home /
Rotate object towards mouse cursor when click
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 15 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 at the cursor with just one click. Thank you in Advance!
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);
}
Use the Transform.LookAt function in LateUpdate for that..
ankit.tiks007 The problem with the Transform.LookAt is that it immediately snaps on the mouse click, and I want the object to smootly turns :)... Or is it there anyway to do that with LookAt?
Thanks for the answer dandago! I got a hint from another guy that my turning should be updated, because the click is too short time wise. $$anonymous$$aybe I can add a boolean, or loop until a condition is met. I will try that tonight.
dandago, I have never heard of iTween.RotateTo() I will check it out in the manual. Thanks man! ;)
Answer by dandago · Jun 06, 2013 at 09:05 AM
You can try solving this easily as follows:
Find out where the mouse is in the game world (as you are doing with ScreenPointToRay).
Translate (move) the ray's intersection point so that its y-coordinate matches that of the object you want to rotate. This is to make sure that the object rotates only left/right towards the object, and not e.g. up/down. To get the intersection point, you will need to use a different overload of Physics.Raycast that takes a RaycastHit out parameter.
use Transform.LookAt() to make the object face the point you calculated above.
If this seems a little complicated, skip #2, and then do it later.
Your answer
Follow this Question
Related Questions
Raycasting and changing player rotation accoording to what is underneath. 0 Answers
Arrow not shooting the in right orientation 0 Answers
Quaternion Slerp help 1 Answer
move object and slow down near end 1 Answer
Instantiate at hit.point 2 Answers