Jump to content

Search In
  • More options...
Find results that contain...
Find results in...

Random motion within a square area

Recommended Posts

I need to animate a bunch of sprites (well, they're animals) within a rectangular (but not square) boundary. I'd like to move them around in a random, non-jittery fashion -- perhaps random bezier curves. I'm also keen to move the ones at the top back in the z-space, and those at the bottom nearer (I suppose I can simply do a loop through each time and map y coord to z coord).


I found some nice Greensock code (posted at the bottom) that will move animals in a circular area, but I need to be able to move within an arbitrary rectangular area (again, of arbitrary ratio, not necessarily square). Is there any other similar code here that would work for that, or is there any easy way to modify this code to make it work (boundary checking? Sin's and cos's are not my forte tonight).


Any help much appreciated!

var xCenter:Number = 275;
var yCenter:Number = 200; 
var poolRadius:Number = 200;
function tweenFish():void {
    var angle:Number = Math.random() * Math.PI * 2; //random angle in radians
    var radius:Number = Math.random() * poolRadius;
    TweenLite.to(fish, 2, {x:Math.cos(angle) * radius + xCenter, y:Math.sin(angle) * radius + yCenter, ease:Quad.easeInOut, onComplete:tweenFish});
Link to comment
Share on other sites

This post here discusses random bezier curves that stay within the confines of the stage:



Keeping an element within a rectangular space (moving left-right, top-bottom) is much easier than circular bounds.

You just need to generate random x/y values within a given range.


something like




var width:Number = 400;
var height:Number = 300;

function tweenFish():void {
    TweenLite.to(fish, 2, {x:randomNumber(0, width), y:randomNumber(0, height), onComplete:tweenFish});

function randomNumber(min:Number, max:Number):Number {
    return Math.floor(Math.random() * (1 + max - min) + min);
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.