Hey guys, I have just started studying Unity and have been trying to find out as much as possible! I love the new 2D features, Well I have been trying to get a 2D Mouse Point/Click system to work. After searching online for a while I didn’t find any good example or tutorial on why or how you should do it, just different code examples that helped me get to this point.
I wanted to help explain this fully so that anyone who might read this could get a real good grasp of how this is working.
I would also like to note I have no idea if this is the proper way to do it by any means, or if there is a more efficient way of doing it, but I at least wanted to share this really quick and simple way of doing it for any newbies out there. This code is in C# if you need help with JS let me know.
Full Code:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public Vector3 targetPosition;
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Mouse0))
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * 5);
}
}
The most important part that I found out and kept giving me the slip up was this line
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Input.MousePosition returns the X/Y coordinates of what I believe to be the ViewPort Coordinates(So basically where your mouse position is within your monitor).
Your objects.Transform point system is related to the WorldPoint coordinate system which is entirely different.
So you would click on a position on the screen and the X/Y coordinates that returned would be (457,640), my player continually moved to the top right hand of the screen. When switching to the WorldPoint system, the coordinates of when you mouse click come back as the correct x/y/z position that your player needs to move correctly towards that position.
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * 5);
This is the final part, there is many different ways of actually performing this step, but this I found to be the most simple. You simply just want to use the built in .MoveTowards method. This function does actually what it looks like it moves you to the targeted position that you give it, Simply provide the correct parameters and boom bada boom, your point click movement system is working.
This is a very short code example, but after the amount of time I spent on it I found it so stupid how little of code was actually needed, so I at least wanted to provide it to anyone who was looking or was wondering how to do it.
If you have any questions feel free to ask and leave any feedback for me, I am still very new to all of this and I would love constructive feedback as well!
Thanks guy.
- Austin