I have a little gnome sitting on a round platform. With a mouse click on the platform I want to rotate the platform around it’s Y axis. The angle depends on the position of the mouse.
My implementation is based on the idea of this thread about how to rotate a door according to mouse movement.
Down below is my full script, which is attached to the platform.
The problem: whenever I click on a random point on the platform, the platform will jump/ flip to an unpredictable rotation angle. I tried to prevent that with the rotationStart = transform.rotation
. Unfortunately this won’t prevent the platform from flipping. What can I do to achieve a smooth rotation?
EDIT: This is the kind of rotation I am trying to achieve:
The left image displays the rotation behavior when applying robertbu’s solution. The red cross symbolizes the mouse click position.
I want the rotation behavior shown on the right image.
Current Code
private var mainCam;
private var firstHitPos;
private var rotationPlane : Plane;
var speed = 0.1;
function Start () {
mainCam = GameObject.FindWithTag("MainCamera");
}
function OnMouseDown(){
var ray = mainCam.camera.ScreenPointToRay(Input.mousePosition);
rotationPlane = new Plane(transform.up, transform.position);
var enter : float;
if(rotationPlane.Raycast(ray , enter)){
firstHitPos = ray.GetPoint(enter);
}
}
function OnMouseDrag(){
var pos = getPlanePos();
var tmpPos = Vector3(pos.x, 0, pos.z);
//var rotationStart= Quaternion.LookRotation(Vector3(firstHitPos.x, 0, firstHitPos.z), transform.up);
var rotationStart= transform.rotation;
var rotationEnd = Quaternion.LookRotation(tmpPos, transform.up);
transform.rotation = Quaternion.Lerp ( rotationStart , rotationEnd, Time.time * speed);
}
function getPlanePos(){
var mousePos = Input.mousePosition;
var ray = mainCam.camera.ScreenPointToRay(mousePos);
var mouseWorldPos = mainCam.camera.ScreenToWorldPoint(Input.mousePosition);
var enter : float;
if(rotationPlane.Raycast(ray , enter)){
var returnVal = mainCam.transform.position + ray.direction.normalized * enter;
return (returnVal);
}
}