- Home /
2D Moving on clicked position
Hello.
I'm working on a 2D game. Today, I came across a big problem. The game is point & click, so I want to be able to click somewhere in the world, and make the character go to that point. I tried some things posted on this forum, but nothing seems to do the job.
PS: I'm using the 2D set for Unity (the 2D option you can choose when starting a new project.)
Answer by robertbu · Dec 02, 2013 at 04:55 AM
Solutions you find on this list for 3D should work for 2D as well. Assuming the camera is at the default position of -10 on the 'z' axis and the sprite is at 0.0 on the 'z' axis, this script will cause an immediate jump of the game object it is attached to based on a mouse click:
#pragma strict
function Update () {
if (Input.GetMouseButtonDown(0)) {
var v3 = Input.mousePosition;
v3.z = 10.0;
v3 = Camera.main.ScreenToWorldPoint(v3);
transform.position = v3;
}
}
Answer by Romano · Feb 03, 2014 at 12:40 PM
This script doesn't include movement, but it has been really important for me to not accept clicks for movement if the player clicks on the character or any items in the game. It should help you get started at least, I've posted the script on my blog, which explains in a bit more detail what the script does: http://notquiteblackandwhite.com/post/75474540217/how-to-do-2d-mouse-clicks-in-unity