Ian Devlin
Ian Devlin

Reputation: 18870

HTML5 canvas object random path generation

I have a canvas object, a circle, that currently animates along a particular path, rather like a bounce. The simple animation code is as follows:

if (x + dx > canvasW || x + dx < 0) dx = -dx;
if (y + dy > canvasH || y + dy < 0) dy = -dy;   
x += dx;
y += dy;

Where dx and dy are set offets to increase the path by.

I'd like to make it follow a random path, such as a fly might.

How would I go about this? Are there any tutorials anyone could point me in the direction of? I've struggled to find any either here or via Google.

Upvotes: 0

Views: 2127

Answers (1)

You can find an implementation of the idea you proposed here. You might want to tweak it a bit but at least it's a start. :)

In case you want to make the trajectory smoother, try evaluating a Bézier curve. Before that you'll have to generate a bunch of points in which to apply the algo.

Upvotes: 2

Related Questions