I want to set up paths for enemy characters in my game to patrol. I'd like to be able to define a list of waypoints and have the enemy follow the path from one point to another, but in a smooth curve.
How can I do this?
I want to set up paths for enemy characters in my game to patrol. I'd like to be able to define a list of waypoints and have the enemy follow the path from one point to another, but in a smooth curve.
How can I do this?
If you want to take a precise mathematical approach, what you're looking for is an interpolation function.
If you have some random points...
... and you want to interpolate (that is, fill in what goes in between). The first thing you're likely to think of is to draw straight lines:
This is called linear interpolation, because the function describing how we interpolate between two points is a linear function; y = m * x + c
kind of deal.
There's nothing stopping us from using a different function to interpolate. Here's an interpolation with a closed B-spline:
It doesn't go through all the points, because basis B-spline control points only influence the shape of the curve.
Cardinal splines, for example, do pass through all points:
I stole the implementations from D3: This is where you'd find the interpolations defined in the D3 source.
Bezier curves are a reasonably simple subset of B-curves (here are some pretty understandable graphics on how they work) and will give good results too. There are others you may want to use; we even have a list.
The other answers all discuss how to draw lines connecting the waypoints, presumably in order to then make the AI character follow the line. I guess that would work, but I prefer an approach where instead of forcing the AI to follow a drawn line, I simply define how the character moves and then use the waypoints as movement targets.
So in other words the waypoint system tells the AI character "walk toward this point" rather than "stick to this line."
For the simplest implementation of such a system, the path is an array of positions, and when the game starts the AI chooses the first position as it's movement target. Once it reaches that target, it switches to the next point in the array. repeat
The path the character takes will naturally smooth between the waypoints if the character's movement characteristics include turning slowly.
(btw if you're wondering what results you get with this technique, the flying puffballs in this demo were implemented in the way I just described)
Take the average of each pair of sequential way-points. Use these as your new start and end point for bezier curves. Use the actual points as control points.
You could also use a weighted average if you only wish to avoid sharp corners.
See this for the complete explanation: How do I generate a smooth random horizontal 2D tunnel?