效果演示

项目介绍

主要源码如下

package top.yunp.starlingcube;

import openfl.display3D.Context3DTriangleFace;
import starling.rendering.Painter;
import starling.events.Event;
import starling.display.Image;
import starling.display.Sprite3D;
import starling.textures.Texture;
import openfl.Assets;
import starling.display.Sprite;

class FirstView extends Sprite {
	private var cube:Sprite3D;

	public function new() {
		super();

		addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
	}

	private function addedToStageHandler(event:Event):Void {
		var bitmapData = Assets.getBitmapData("assets/girl.png");
		var texture = Texture.fromBitmapData(bitmapData);
		cube = createCube(texture);
		cube.x = stage.stageWidth / 2;
		cube.y = stage.stageHeight / 2;
		cube.z = 300;
		addChild(cube);

		addEventListener(Event.ENTER_FRAME, enterFrameHandler);
	}

	private function enterFrameHandler(event:Event):Void {
		cube.rotationX += 0.005;
		cube.rotationY += 0.005;
	}

	private function createCube(texture:Texture):Sprite3D {
		var offset:Float = texture.width / 2;

		var front:Sprite3D = createSidewall(texture);
		front.z = -offset;

		var back:Sprite3D = createSidewall(texture);
		back.rotationX = Math.PI;
		back.z = offset;

		var top:Sprite3D = createSidewall(texture);
		top.y = -offset;
		top.rotationX = Math.PI / -2.0;

		var bottom:Sprite3D = createSidewall(texture);
		bottom.y = offset;
		bottom.rotationX = Math.PI / 2.0;

		var left:Sprite3D = createSidewall(texture);
		left.x = -offset;
		left.rotationY = Math.PI / 2.0;

		var right:Sprite3D = createSidewall(texture);
		right.x = offset;
		right.rotationY = Math.PI / -2.0;

		var cube:Sprite3D = new Sprite3D();
		cube.addChild(front);
		cube.addChild(back);
		cube.addChild(top);
		cube.addChild(bottom);
		cube.addChild(left);
		cube.addChild(right);

		return cube;
	}

	private function createSidewall(texture:Texture):Sprite3D {
		var image:Image = new Image(texture);
		image.alignPivot();

		var sprite:Sprite3D = new Sprite3D();
		sprite.addChild(image);

		return sprite;
	}

	public override function render(painter:Painter):Void {
		painter.pushState();
		painter.state.culling = Context3DTriangleFace.BACK;
		super.render(painter);
		painter.popState();
	}
}