How can I limit the speed in this script?

Hi,

I’m starting to work with Javascript and I made this script:

var rotSpeed = 5.0;

function Update () {

// Player looks at mouse

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);
    var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);

    transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotSpeed * Time.deltaTime);
  
}

// Player runs when LMB is pressed.The speed is adjusted by the distance from the player to the mouse.

if (Input.GetKey (KeyCode.Mouse0)){
       
transform.Translate(0.0, 0.0, (Vector3.Distance(targetPoint,transform.position)/5)* Time.deltaTime);   
}     

}

Since the speed is calculated by the distance from the player to the mouse I’d like to set a maximum speed so it behaves correctly. But I don’t know how to do it. Can you guys help me?

Thank you, and sorry for my english. I’m from Spain.

Haven’t tested this code, but it might work anyway… Hope I didn’t misunderstand what you are trying to do, greetings from germany :wink:

    var rotSpeed = 5.0;
    var maxSpeed = 10.0; //this value can be adjusted
    var move = 0.0;
    
    function Update () {
    
    // Player looks at mouse
    
    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);
        var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
    
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotSpeed * Time.deltaTime);
    
    }
    
    // Player runs when LMB is pressed.The speed is adjusted by the distance from the player to the mouse.
    
    if (Input.GetKey (KeyCode.Mouse0)){
    
      //check if mouse distance is bigger than max speed variable
    
      if(Vector3.Distance(targetPoint,transform.position)/5 > maxSpeed)
      {
      move = maxSpeed;
      }
      else
      {
      move = Vector3.Distance(targetPoint,transform.position)/5;
      }
    
    transform.Translate(0.0, 0.0, move * Time.deltaTime);   
    
    }

 }