Actionscript:
-
var pointNum:int = 20000;
-
var radius:int = 150;
-
-
var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
-
addChild(new Bitmap(canvas));
-
var verts:Vector.<Number> = new Vector.<Number>();
-
var pVerts:Vector.<Number> = new Vector.<Number>();
-
var uv:Vector.<Number> = new Vector.<Number>();
-
-
for (var i:int = 0; i<pointNum; i+=3){
-
var xp:Number = Math.random() * 400 - 200;
-
var yp:Number = Math.random() * 400 - 200;
-
var zp:Number = Math.random() * 400 - 200;
-
var dist:Number = Math.sqrt(xp * xp + yp * yp + zp * zp);
-
// normalize and scale x,y,z
-
verts[i] = xp / dist * radius;
-
verts[i+1] = yp / dist * radius;
-
verts[i+2] = zp / dist * radius;
-
}
-
-
var m:Matrix3D = new Matrix3D();
-
var dx:Number = 0, dy:Number = 0;
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
m.identity();
-
dx += (mouseX - dx) / 4;
-
dy += (mouseY - dy) / 4;
-
m.appendRotation(dx, Vector3D.X_AXIS);
-
m.appendRotation(dy, Vector3D.Y_AXIS);
-
m.appendTranslation(200,200,0);
-
Utils3D.projectVectors(m, verts, pVerts, uv);
-
canvas.fillRect(canvas.rect, 0x000000);
-
for (var i:int = 0; i<pVerts.length; i+=2){
-
canvas.setPixel(pVerts[i], pVerts[i + 1], 0xFFFFFF);
-
}
-
}
This snippet shows a quick way to randomly place a bunch of xyz coordinates on the surface of a sphere. I saw this trick in an OpenGL book a few years back - dug around my books but couldn't find it... If I find it I'll update this post.
The trick is achieved by normalizing the vector defined by each 3D coordinate...
4 Comments
Hi Zevan
it’s not related but i found this fun reading for me (via @NeuroProd) http://www.cs.brown.edu/courses/cs123/lectures.htm
that looks like its a very good link… thanks katopz
Hi, awesome demos. I particularly like the spring one and how it can mess with your depth perception. This random point generator is slightly biased. In fact you can see a rough outline of a cube superimposed on the sphere. You can avoid this by throwing away all points which were originally greater than 200 units from the origin.
Hey andre, glad you like the demos… there are a few other ways than throwing away points… but I actually like that aspect of this demo…. you could even use the same technique as the sphere of squares post from a few days back…. you could also use a little trig which is basically the same thing as using Matrix3D….
Anyway… I was wondering if someone would notice that… you have a good eye, I just think it’s cool that normalizing the vectors creates a sphere… first time I saw that trick was in some OpenGL book that I think I lost (because I can’t seem to find it).