Inverting rotation in 3D, to make an object always face the camera?

前端 未结 4 916
暗喜
暗喜 2020-12-01 03:49

i have lots of sprites arranged in 3D space, and their parent container has rotations applied. How do i reverse the sprites 3D rotation, that they always face the camera (Ac

4条回答
  •  情话喂你
    2020-12-01 04:33

    I've solved it using Wikipedia, matrices and black magic. I choose to implement custom rotation instead of inverting the rotation of all objects. Heres the code if anyones interested:

    package{
    import flash.display.Sprite;
    import flash.events.Event;
    
    public class test extends Sprite{
    
    private var canvas:Sprite = new Sprite();
    private var sprites:Array = []
    private var rotx:Number=0,roty:Number=0,rotz:Number=0;
    private var mm:Matrix3 = new Matrix3();
    public function test(){
        addChild(canvas);
        canvas.x = canvas.y = 230
        for (var i:int=0;i<30;i++){
            var sp:Sprite = new Sprite();
            canvas.addChild(sp);
            sp.graphics.beginFill(0xFF0000);
            sp.graphics.drawCircle(0,0,2);
            sp.x = Math.random()*200-100;
            sp.y = Math.random()*200-100;
            sp.z = Math.random()*200-100;
            sprites.push(sp);
            rotx=0.06; //from top to bottom
            //roty=0.1; //from right to left
            rotz=0.1; //clockwise
            mm.make3DTransformMatrix(rotx,roty,rotz);
        }
        addEventListener(Event.ENTER_FRAME,function():void{
            for (var i:int=0;i

    and the matrix3 class:

    public class Matrix3{
    
        private var da:Vector.; // rows
    
        public function make3DTransformMatrix(rotx:Number,roty:Number,rotz:Number):void{
            var cosx:Number = Math.cos(rotx);
            var cosy:Number = Math.cos(roty);
            var cosz:Number = Math.cos(rotz);
            var sinx:Number = Math.sin(rotx);
            var siny:Number = Math.sin(roty);
            var sinz:Number = Math.sin(rotz);
            da =    new [
                cosy*cosz, -cosx*sinz+sinx*siny*cosz,  sinx*sinz+cosx*siny*cosz,
                cosy*sinz, cosx*cosz+sinx*siny*sinz , -sinx*cosz+cosx*siny*sinz,
                -siny    ,         sinx*cosy        ,        cosx*cosy         ];
        }
    
        public function rotateByAngles(d:DisplayObject):void{
            var dx:Number,dy:Number,dz:Number;
            dx = da[0]*d.x+da[1]*d.y+da[2]*d.z;
            dy = da[3]*d.x+da[4]*d.y+da[5]*d.z;
            dz = da[6]*d.x+da[7]*d.y+da[8]*d.z;
            d.x = dx;
            d.y = dy;
            d.z = dz;
        }
    }
    }
    

提交回复
热议问题