How can I move an object to the mouse with a specific speed? I mean like it moves towards the mouse with (20px/s) and its not matter how far the mouse is. My code is:
public class PlayerMovement : MonoBehaviour
{
private Vector3 mousePosition;
public float moveSpeed = 0.02f;
void Update()
{
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
mousePosition.z = Camera.main.nearClipPlane;
transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed * Time.deltaTime);
}
}
Because using this (This is the only code I found online) if the mouse is far away the object move faster.
-Thanks!
CodePudding user response:
That is what lerp
does by definition. You can use MoveTowards
instead.
transform.position = Vector2.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
CodePudding user response:
void Update()
{
Vector3 farePos=Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,10f));
transform.position=new Vector3(farePos.x,transform.position.y,transform.position.z);
}
** This code moves the object left and right with the mouse. You can bind the code to the object and use it. He usually does my job.**