Move towards mouse position on button down (2D)?

Hey everyone, so I have an astronaut character (in zero gravity) in 2d, and I’m just trying to get it to move towards the mouse position when I’m holding down the left mouse key. Right now if I click and hold on the right side of the screen the astronaut moves towards the mouse pos, but if I click and hold on the left side of the screen the character moves away from the mouse, so I’m kind of confused. My script is simple enough so if anyone can see the problem or can offer any improvements, I’d appreciate it. Also, the astronaut is a ragdoll, so that’s why the force is being applied to a child of the astronaut (the main body of the ragdoll).

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

Rigidbody2D rigid2D;
public float speed;
public float acceleration;
public float deceleration;
public float maxSpeed;

void Start ()
{
rigid2D = transform.GetChild(1).GetComponent<Rigidbody2D>();
}

void Update ()
{
if (Input.GetMouseButton(0))
{
if (speed <= maxSpeed)
{
speed = speed + acceleration * Time.deltaTime;
}
else
{
speed = maxSpeed;
}

Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else
{
if (speed > 0)
{
speed = speed - deceleration * Time.deltaTime;
}
else
{
speed = 0;
}
}
}
}
``````

Right now the way you are calculating the force to apply does not represent any direction. To get a direction you can subtract 2 positions, for example something like `mousePos - transform.position`. However, mousePos is a 2D vector therefore you will need to properly convert it to correspond to the plane your astronaut moves in. If it is the XY plane you can just use it as is, otherwise you need to use `Vector3 mousePos3 = new Vector3(mousePos.x, 0, mousePos.y)` for the XZ plane.

So you can try something like this:

``````Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos - transform.position;	//if astronaut is in XY plane

rigid2D.AddForce(direction.normalized * speed);	//normalize direction to make the movement speed independent from distance and only controlled by the speed variable
``````