title: Unity move towards mouse position for limited distance
body: <p>I am working on a top-down 2D game project. The character must follow the mouse cursor all the time, this is what I could do so far. I also want the character to slide towards the mouse for a limited distance when clicked.</p>
  <p>So let's say the character position is: 0, 0, 0
  Mouse click position: 8, 4, 0
  When clicked, the character must move towards the mouse click position but only for a limited distance, so it must not reach if distance more than 2. So the final character location should be: 2, 2, 0</p>
  <p>How can I achieve that? Here is my code;</p>
  <pre><code>using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class PlayerMovemetn : MonoBehaviour
  {
  
      private float speed = 4;
      private float slideSpeed = 8;
      private Vector3 targetPosition;
      private bool isMoving = false;
  
      void Update()
      {
          SetTargetPosition();
  
          if (Input.GetMouseButton(0))
          {
              //Slide 2 meters towards mouse location (with the speed of slideSpeed variable)
          }
          
          if (isMoving)
          {
              Move();
          }
  
          
      }
  
      void SetTargetPosition()
      {
          targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
  
          targetPosition.z = transform.position.z;
  
          isMoving = true;
      }
  
      void Move()
      {
          transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
  
          if (transform.position == targetPosition)
          {
              isMoving = false;
          }
      }
  }
  </code></pre>