Help with Smooth Rotation

Hello,

If someone could help that would be great as I am quite new at this. I am trying to get my Transform to to slowly rotate towards target left mouse click then move. With this code the Transform does not fully rotate towards left mouse click unless Rotation speed is high and there is no smooth rotation at all. The movement is jerky. Any help would be much appreciated

Thanks

// Click To Move script // Moves the object towards the mouse position on left mouse click

var moveSpeed:int; // Determines how quickly Transform moves towards position var rotateSpeed : float; // Determines how quickly to rotate

private var targetPosition :Vector3 ;

// Set up Variables before game starts

function Awake() { targetPosition = transform.position; // set Target position to current position of selected Transform }

function Update () {

if(Input.GetKeyDown(KeyCode.Mouse0))
{
    var playerPlane = new Plane(Vector3.up, transform.position);
    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    var hitdist = 0.0;

    if (playerPlane.Raycast (ray, hitdist)) 
    {
        var targetPoint = ray.GetPoint(hitdist);
        targetPosition = ray.GetPoint(hitdist);
  var targetRotation = Quaternion.LookRotation(targetPosition- transform.position);
       transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotateSpeed * Time.deltaTime);

    }

}

transform.position = Vector3.MoveTowards(transform.position,targetPosition,Time.deltaTime * moveSpeed);

}

1 Answer

1

I dont see an immediate problem with this although a pro may come laong and say otherwise. Try changing `Update` to `FixedUpdate` in order to get a more consistent update rate. or alternatively you could just remove the `Time.deltaTime` from `rotateSpeed * Time.deltaTime` then your object will move at the speed of the rotation you have set only instead of the rotation you have set multiplied by the length of time it took to complete the last frame. (which is usually less than one so this is why you would have to normally change rotation speed up and with time.deltaTime being inconsistent could be the reason for your jerkiness)

EDIT

try removing the rigidbody and see if it yields any different result? Try also changing `var playerPlane = new Plane(Vector3.up` to `var playerPlane = new Plane(Vector3.forward`