Flashで作る3Dのお勉強2
Flashで作る3Dのお勉強2
Zソートをやってみる
/**
* Copyright ta6b ( http://wonderfl.net/user/ta6b )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/dkIp
*/
//Flashで作る3Dのお勉強2
//Zソートをやってみる
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.text.TextField;
import flash.ui.Keyboard;
[SWF(backgroundColor=0x333333, frameRate=60)]
public class Test3D extends Sprite
{
private var plates:Array;
private var numPlates:int = 50;
private var focalLength:Number = 250;
private var vpX:Number = stage.stageWidth / 2;
private var vpY:Number = stage.stageHeight / 2;
private var top:Number = -250;
private var bottom:Number = 250;
private var left:Number = -250;
private var right:Number = 250;
private var front:Number = 250;
private var back:Number = -250;
function Test3D()
{
init();
}
private function init():void
{
plates = new Array();
for (var i:int = 0; i < numPlates; i++){
var plate = new Plate();
plates.push(plate);
plate.vx = Math.random() * 10 - 5;
plate.vy = Math.random() * 10 - 5;
plate.vz = Math.random() * 10 - 5;
addChild(plate);
}
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
private function enterFrameHandler(e:Event):void
{
for (var i:int = 0; i < numPlates; i++) {
var plate:Plate = plates[i];
move(plate);
}
sortZ();
}
private function move(plate:Plate):void {
var radius:Number = plate.radius;
plate.xpos += plate.vx;
plate.ypos += plate.vy;
plate.zpos += plate.vz;
if (plate.xpos + radius > right)
{
plate.xpos = right - radius;
plate.vx *= -1;
}else if (plate.xpos - radius < left){
plate.xpos = left + radius;
plate.vx *= -1;
}
if (plate.ypos + radius > bottom)
{
plate.ypos = bottom - radius;
plate.vy *= -1;
}else if (plate.ypos - radius < top){
plate.ypos = top + radius;
plate.vy *= -1;
}
if (plate.zpos + radius > front)
{
plate.zpos = front - radius;
plate.vz *= -1;
}else if (plate.zpos - radius < back){
plate.zpos = back + radius;
plate.vz *= -1;
}
if(plate.zpos>-focalLength){
var scale:Number = focalLength / (focalLength + plate.zpos);
plate.scaleX = plate.scaleY = scale;
plate.x = vpX + plate.xpos * scale;
plate.y = vpY + plate.ypos * scale;
plate.visible = true;
}else {
plate.visible = false;
}
}
private function sortZ():void {
plates.sortOn("zpos", Array.DESCENDING | Array.NUMERIC);
for (var i:int = 0; i < numPlates; i++) {
var plate:Plate = plates[i];
setChildIndex(plate, i);
}
}
}
}
import flash.display.Sprite;
internal class Plate extends Sprite
{
private var w:Number = 100;
public var radius:Number;
public var xpos:Number = 0;
public var ypos:Number = 0;
public var zpos:Number = 0;
public var vx:Number = 0;
public var vy:Number = 0;
public var vz:Number = 0;
function Plate(radius:Number = 50)
{
this.radius = radius;
graphics.lineStyle(1, 0xff0000);
graphics.beginFill(0xffffff);
graphics.drawRect( -w / 2, -w / 2, w, w);
graphics.endFill();
}
}