Draw a 2D Path in Unity for your character to follow
There seem to be plenty of examples about how to draw a path that your character can follow in Unity 3D (emphasis on 3D), but I’m working in a 2D game, and couldn’t find what I needed. Here’s how you can draw a path in Unity 2D by using the Line Renderer. Some key points:
- I wrapped the Line Renderer in a custom class to track the actual path (hard to do with just the Line Renderer itself).
- I used prefabs although you don’t need to.
- To detect the mouse location accurately, given I had no other objects on the canvas, I needed to use a plane to cast rays and find the world coordinates.
Here is the relevant source code (full source on GitHub):
Plane plane = new Plane(Camera.main.transform.forward * -1, position); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (plane.Raycast(ray, out float distance)) { if (pathGameObject == null) { // Starting a new line. Instantiate our "Path Object" pathGameObject = UnityEngine.Object.Instantiate(LinePrefab).GetComponent<PathGameObject>(); } else { // TODO: Check distance between points. This just adds all of them, even // if you hold the mouse still. Vector3 hitpoint = ray.GetPoint(distance); pathGameObject.AddPosition(hitpoint); } }
Also, if you like code AND science fiction, check out my book on Amazon (shameless plug).
Finally, if you’re interested in the 3D example, check out this YouTube preso.