Forums: Flash:

 

AS2 - getting a random point a set distance away

first
 

baron ruhstoff AS2 - getting a random point a set distance away

I have a point p. I need a second point - p2 - a set distance d away (i.e. on the circumference of a circle with radius d).

The first thing that comes to mind is the Pythagorean Theorem:
var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));

...but before I attempt to bring back what I learned in high school geometry class, I figured I would see if any folks know of a better way. Any suggestions?


...........................
site chiggety check!
quote
 

baron ruhstoff

Got it:

	// return a randomly selected point a fixed distance away from a given point
private function getPointWithinRange(x:Number, y:Number, d:Number):Object {
var objPoint:Object = new Object();
var nSides:Number = 200;
var nRand:Number = randRange(1,nSides);
var pointRatio:Number = nRand/nSides;
var xSteps:Number = Math.cos(pointRatio*2*Math.PI);
var ySteps:Number = Math.sin(pointRatio*2*Math.PI);
objPoint.x = x + xSteps * d;
objPoint.y = y + ySteps * d;
return objPoint;
}


...........................
site chiggety check!
quote
 

mystic_juju

just been doing something like this in pv3d...needed x,y,z. posting in case anybody finds this useful.


var x:Number = r * (Math.cos(ang1) * Math.cos(ang2));
var y:Number = r * Math.sin(ang1);
var z:Number = r * (Math.cos(ang1) * Math.sin(ang2));

A tale that begins with a beet will end with the devil
quote
 

lithium

You can do it a bit simpler with something like this: ( the majority of this code is testing. the getPoint() method is all you need )

function getPoint ( from : Point, radius : Number ) : Point
{
var angle : Number = Math.random() * 360;
var px : Number = from.x + Math.sin ( angle * Math.PI / 180 ) * radius;
var py : Number = from.y + Math.cos ( angle * Math.PI / 180 ) * radius;

return new Point ( px, py );
}

// Test code.

var radius : Number = 100;

var homePoint : Point = new Point ( 100, 100 );
var destPoint : Point = getPoint ( homePoint, radius );

this.graphics.beginFill ( 0xFF0000 );

this.graphics.drawEllipse( homePoint.x, homePoint.y, 10, 10 );
this.graphics.drawEllipse( destPoint.x, destPoint.y, 10, 10 );

// Test distance;

var dx : Number = homePoint.x - destPoint.x;
var dy : Number = homePoint.y - destPoint.y;

var distance : Number = Math.round ( Math.sqrt ( dx * dx + dy * dy ) );

trace ( "distance: " + distance );
trace ( "distance == radius? : " + ( distance == radius ) );


hope it helps,

A.

 

baron ruhstoff

lith.ftw++;


...........................
site chiggety check!
quote
 
first
 

Forums: Flash: AS2 - getting a random point a set distance away

 
New Post
 
You must be logged in to post