Point to click movement in a 2d game

Hello. I have been looking for a way to move a game object based on a mouse click.
Any help at this point would be appreciated.

Well. In 3D you could raycast down from mouse click to hit a collider, and determine stuff from there - but now with 2D I think it actually will need to be done differently.

I am not sure off the top of my head how a basic implementation would be done, but some more info would probably help others to help you:

  • is it a “top-down” or “side-scroller” game?
  • using all 2d physics I’m guessing?
  • have you tried anything already?

Anyway if I come up with an idea I’ll be sure to post about it.

(FROM: Find Mouse co-ordinates on click in a 2d environment - Questions & Answers - Unity Discussions )

If you read about that to grasp the idea, then take mouse position, compare to your characters position, and decide movement based on that.

Good luck!

PS my bad didn’t mean to double post, meant to edit…

Black,
Here’s what I did (note: this is for C#):

// Define a variable vector for the position you will want the object to move to.
Vector3 wantedPos;
// Get the position of the mouse click.
Vector3 mousePos = Input.mousePosition;
// Transmogrify the mouse coordinates to the coordinate system of your game space.
wantedPos = Camera.main.ScreenToWorldPoint (new Vector3 (mousePos.x, mousePos.y, 1f));
// Determine the vector from your desired (ending) position and the game objects current position.
Vector3 relativePos = wantedPos - transform.position ;
// Move your game object using a rigid body force to get it moving in the right direction.
transform.rigidbody2D.AddForce(relativePos.normalized * 40f);

Instead of doing the AddForce, you could also use iTween; it’s a free download.
Then you can do something like this: iTween.MoveTo(gameObject,wantedPos,2);
That will cause a game object to move to the desired location in 2 seconds.

Hope this helps.
I’m struggling with this stuff too.

– Paul

great answer :slight_smile:

indeed, a very helpful answer

if you have the object in the screen and you want it to move to anyplace you mousepress just give the object a 3d collider and make the collider big enough to cover the screen (dont use it as a trigger ) and if you ot onMousePressed working it will transport the object to the clicking position