Wednesday, July 10, 2013

Unity: Creating dynamic lines

I learned how to program using Java, specifically a development interface called Processing, which I heartily recommend to anyone thinking about trying it. The work I did was in 2D, and as I grappled with vector math and time slices, I found it very handy to draw a line from an object I was moving to the point it was moving to. This illuminated what the object was thinking, something traditionally difficult to do during runtime, and it was as easy as saying "draw a line from this point to this point."

When I started using Unity, I didn't have this option. It was impossible to say "draw a line from this point to this point," at least in such simple terms, and as I grappled with vector math (again, but in three dimensions!) I felt out of touch and frustrated when I was forced to interpret what was going on, rather than knowing at a glance.

Lucky for us, I found a solution, and I've been using it ever since. Although my grasp of vectors is much tighter these days, it's always a treat to write artificial intelligence that, say, takes a mob through the floor and into the void beneath, rather than to a point of interest. In those cases, where the object is making its own decisions, it's good to know what it's "looking at." And that's when the Magic Lines come into play.

Okay, it's actually called Line Renderer, but where's the fun in that?

A Line Renderer component can be used for motion trails, telephone wires, hanging vines, and a whole lot of other fun visual tricks, but here we're just going to draw a line in space, from one point to another. Here's the code:
LineRenderer magicLine;

void DrawLineToPosition (Vector3 targetPosition)
 // If we haven't created the LineRenderer yet, do so
 if (!magicLine)
  magicLine = gameObject.AddComponent;
  // Give it only two points: one for "here", one for "there
  // The "line" is actually a polygon, and here we can make it taper a bit at the end
  // In effect, it points at the target position
  magicLine.SetWidth(1, 0.1);
    magicLine.SetPosition(0, transform.position);
    magicLine.SetPosition(1, targetPosition);

No comments:

Post a Comment