- Home /
Mouse Player Movement Controller
I've been looking for a script where the player mirrors the mouse movement but doesn't snap to the mouse position. This is my current script:
private Vector3 mousePosition;
private Rigidbody2D rb;
private Vector2 direction;
private float moveSpeed = 100f;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
if (Input.GetMouseButton(0))
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
direction = (mousePosition - transform.position).normalized;
rb.velocity = new Vector2(direction.x * moveSpeed, direction.y * moveSpeed);
}
else
{
rb.velocity = Vector2.zero;
}
Feel free to modify this script or create a new one. Thanks.
@alexpensotti Have you thought about using Transform.Translate?
Answer by xxmariofer · Apr 05, 2019 at 01:41 PM
may i ask what do you mean by snap to the mouseposition? that it continues in the direction of the mouse rather than stopping?
that would be as easi as changing your script to this
if(Input.GetMouseButtonDown(0))
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
direction = (mousePosition - transform.position).normalized;
}
if (Input.GetMouseButton(0))
{
rb.velocity = direction * moveSpeed;
}
else
{
rb.velocity = Vector2.zero;
}
Your answer
Follow this Question
Related Questions
How do I setup fixed movement between predetermined tiles? 0 Answers
Making a bubble level (not a game but work tool) 1 Answer
,I am trying to code a dash in c#. I cant get it, help! 1 Answer
How do i maintain the same speed in the air? 1 Answer
How can I move a player toward a gameobject by clickling an image 0 Answers