Moving an object along a 2D plane

I’m learning C# and am trying to make a simple scene with a ball where you click it, pull the mouse, release and it should launch in the opposite direction.

I’ve gotten the scene to work but for some reason it sticks to only 2 dimensions and not the two I actually need.

Here is the code I’ve got so far. What I need help with is figuring out why I’m stuck on 2 axis but no matter which axis I lock to 0, the ball never moves on the x,z axis (the result I want).

	Vector3 mMouseDownPos;
	Vector3 mMouseUpPos;

	public float speed = .1f;

	// Use this for initialization
	void Start () 
	{

	}
	
	// Update is called once per frame
	void Update () 
	{

	}
	
	void OnMouseDown() 
	{
		mMouseDownPos = Input.mousePosition;
		Debug.Log( "the mouse down pos is " + mMouseDownPos.ToString() );
		mMouseDownPos = Input.mousePosition;
		var MouseDownPos = 1;
		Debug.Log( "the mouse down pos is " + mMouseDownPos.ToString() );
		mMouseDownPos.z = 0;
    }
	
	void OnMouseUp() 
	{
		mMouseUpPos = Input.mousePosition;
		mMouseUpPos = Input.mousePosition;
		mMouseUpPos.z = 0;
		var MouseUpPos = 1;
		var direction = mMouseDownPos - mMouseUpPos;
		direction.Normalize();
		rigidbody.AddForce (direction * speed);
		Debug.Log( "the mouse up pos is " + mMouseUpPos.ToString() );
	}

}

As I said, I’m extremely new to C# so any help would be appreciated. Thanks.

Your title is a bit misleading. You are trying to move an object along a 2D plane in 3D space. Usually when someone refers to 2D they are talking a a 2D game. You have several technical issues here that will take a bit of time for you to work out. The first is that Input.mousePosition() is in screen coordinates. Your balls are in world coordinates in 3D space. Your camera is not parallel to the ground plane, so making this translation is a bit more of a challenge than usual.

Assuming the ground plane is flat, one way to solve this problem would be to construct a mathematical plane using Unity’s Plane class. Assuming the ground plane is oriented on the XZ axes, then you will use Vector3.up for the normal of the plane. The plane will be up from the origin so that it passes through the center of the striker ball.

To find positions in world space, using the plane, construct a ray from the mouse position, and use Plane.RayCast() to get the position.

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float f;
if (Plane.Raycast(ray, out f)
   mMouseDownPos = Ray.GetPoint(f);

You will need the same calculation for mMouseUpPos. Your direction and AddForce calculations look fine.