Siva
Siva

Reputation: 359

AS3:Rotate an multiple objects towards their random point

Mr.Taurayi the solution which you gave is really wonderfull. But i don't want to do that in enter frame. I just tweening the object to rotate to the random positions. so let me know the conditions for the rotations. i mean the object should rotate towards the random point. for eample. if( dx < 0){

                    dx += 360;
                    dy += 360; 
                    angl = Math.atan(dy/dx) + deg2rad(90)
                    InsectsVector[i].rotation = angl;
                }

                if(dx >= 360){

                    dx  -=  360;
                    dy  -=  360;
                    angl = Math.atan(dy/dx) + deg2rad(90)
                    InsectsVector[i].rotation = angl;
                }

                if ( dy > 180 )
                {
                    dx -= 360;
                    dy -= 360
                    angl = Math.atan(dy/dx) + deg2rad(-90);
                    InsectsVector[i].rotation = angl;
                }

                if ( dx < -180 )
                {
                    dx += 360;
                    dy += 360;
                    angl = Math.atan(dy/dx) + deg2rad(90)
                    InsectsVector[i].rotation = angl;
                }

this condition above is not working properly in the below coding . so please let me know this.

    Please its very urgent dudes. And thanks in advance for replying. 
  private function InsectsRandPos():void{

        randNum_1 = uint(Math.random()*50);
        for (var i:uint=0; i < InsectsVector.length; i++){
            while(InsecNode.indexOf(randNum_1) != -1){
                randNum_1 = uint(Math.random()*50);
            }
            InsecNode[i] = randNum_1;
            randPointForInsec = nodeContainer.getNodePostion(InsecNode[i]);

            if(spNode != InsecNode[i]){ 
                InsectsVector[i].visible = true;
                nodeContainer.addChild(InsectsVector[i]);

                var dx:Number =  randPointForInsec.x - InsectsVector[i].x ;
                var dy:Number =  randPointForInsec.y - InsectsVector[i].y ;
                var angl:Number   = Math.atan(dy/dx) + deg2rad(90);
                InsectsVector[i].rotation = angl; //  (angl*-1)+180;

                if( dx < 0){

                    dx += 360;
                    dy += 360; 
                    angl = Math.atan(dy/dx) + deg2rad(90)
                    InsectsVector[i].rotation = angl;
                }

                if(dx >= 360){

                    dx  -=  360;
                    dy  -=  360;
                    angl = Math.atan(dy/dx) + deg2rad(90)
                    InsectsVector[i].rotation = angl;
                }

                if ( dy > 180 )
                {
                    dx -= 360;
                    dy -= 360
                    angl = Math.atan(dy/dx) + deg2rad(-90);
                    InsectsVector[i].rotation = angl;
                }

                if ( dx < -180 )
                {
                    dx += 360;
                    dy += 360;
                    angl = Math.atan(dy/dx) + deg2rad(90)
                    InsectsVector[i].rotation = angl;
                }

                var InsectTwee:Tween = new Tween(InsectsVector[i], 5, Transitions.LINEAR );
                InsectTwee.animate("x", randPointForInsec.x);      
                InsectTwee.animate("y", randPointForInsec.y);
                Starling.juggler.add(InsectTwee);

            }

            else if(spNode == InsecNode[i]){
                var obj:Object = new Object(); 
                obj = InsectsVector[i];
                obj.visible = false;
                trace("obj  .name ..."+obj + "   InsectsVector[i] :"+InsectsVector[i])
            }
        }   
    }

Upvotes: 0

Views: 1087

Answers (1)

Taurayi
Taurayi

Reputation: 3207

It's a little hard to understand your question. I made an example from my understanding of what I thought you were asking for:

[UPDATED]

package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.TimerEvent;
    import flash.geom.Point;
    import flash.utils.Timer;

    /**
     * ...
     * @author 
     */
    public class Main extends Sprite 
    {
        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);

        }// end function

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            for (var i:int = 0; i < 20; i++) {

                var npc:NPC = new NPC();
                npc.addEventListener(NPC.MOVE_COMPLETE, onMoveComplete);
                npc.setDelay(5000);
                npc.setPoints(getRandomPoint(), getRandomPoint());
                npc.updateRotation();
                npc.move();

                addChild(npc);

            }// end for

        }// end function

        private function onMoveComplete(e:Event):void {

            var npc:NPC = e.target as NPC;
            npc.removeEventListener(NPC.MOVE_COMPLETE, onMoveComplete);
            npc.setPoints(npc.getPoint(), getRandomPoint());
            npc.addEventListener(NPC.ROTATION_COMPLETE, onRotationComplete);
            npc.rotate();

        }// end function

        private function onRotationComplete(e:Event):void {

            var npc:NPC = e.target as NPC;
            npc.removeEventListener(NPC.ROTATION_COMPLETE, onRotationComplete);
            npc.addEventListener(NPC.MOVE_COMPLETE, onMoveComplete);
            npc.move();

        }// end function

        private function getRandomPoint():Point {

            var randomX:Number = Math.random() * stage.stageWidth;
            var randomY:Number = Math.random() * stage.stageHeight;

            return new Point(randomX, randomY);

        }// end function

    }// end class

}// end package

import flash.display.Sprite;
import flash.display.Shape;
import flash.events.Event;
import flash.geom.Point;
import flash.utils.Timer;
import flash.events.TimerEvent;
class NPC extends Sprite {

    public static const MOVE_COMPLETE:String = "moveComplete";
    public static const ROTATION_COMPLETE:String = "rotationComplete";
    private var _to:Point;
    private var _from:Point;
    private var _timer:Timer;
    private var _delay:Number;

    public function get from():Point { 

        return _from; 

    }// end function

    public function get to():Point {

        return _to; 

    }// end function

    public function NPC() {

        addShape();

    }// end function

    public function setDelay(delay:Number):void {

        _delay = delay;

    }// end function

    public function setPoints(from:Point, to:Point):void {

        this._from = from;
        this._to = to;

        this.x = from.x;
        this.y = from.y;

    }// end function

    public function move():void {

        if (!this._to || !this._from)
            throw new Error("to and from points must be set");

        if (!_delay)
            throw new Error("delay must be set");

        addTimer();

    }// end function

        public function rotate():void {

            this.addEventListener(Event.ENTER_FRAME, onRotationEnterFrame);

        }// end function

        private function onRotationEnterFrame(e:Event):void
        {
            var dAngle:int = (getAngle() - this.rotation) % 360;

            if (dAngle < -180) {

                dAngle += 360;

            }
            else if (dAngle > 180) {

                dAngle -= 360;

            }// end if

            if (dAngle < 0) {

                --this.rotation;

            } else { 

                ++this.rotation;

            }// end if

            if (dAngle == 0) {

                removeEventListener(Event.ENTER_FRAME, onRotationEnterFrame);
                dispatchEvent(new Event(NPC.ROTATION_COMPLETE));

            }// end if

        }// end function

    private function addShape():void {

        var shape:Shape = new Shape();
        shape.graphics.lineStyle(1, 0x000000);
        shape.graphics.drawRect(-10, -10, 20, 20);
        shape.graphics.endFill();
        shape.graphics.beginFill(0x000000);
        shape.graphics.moveTo(-10, -10);
        shape.graphics.lineTo(0,-10);
        shape.graphics.lineTo(-10, 0);
        shape.graphics.lineTo( -10, -10);
        shape.rotation = 45;
        addChild(shape);

    }// end function

    private function addTimer():void {

        this.addEventListener(Event.ENTER_FRAME, onEnterFrame);

        _timer = new Timer(_delay, 1);
        _timer.addEventListener(TimerEvent.TIMER, onTimer);
        _timer.start();

    }// end function

    private function onTimer(e:Event):void {

        removeTimer();

    }// end function

    private function removeTimer():void {

        _timer.removeEventListener(TimerEvent.TIMER, onTimer);
        removeEventListener(Event.ENTER_FRAME, onEnterFrame);

        dispatchEvent(new Event(NPC.MOVE_COMPLETE));

    }// end function

    private function onEnterFrame(e:Event):void {

        var dPoint:Point = getDPoint();
        this.x += dPoint.x;
        this.y += dPoint.y;

        if (_to.equals(getPoint())) {

            removeTimer();

        }// end if

    }// end function

    private function getDPoint():Point {

        var point:Point = _to.subtract(_from);
        point.normalize(1);
        return point;

    }// end function

    public function getPoint():Point {

        return new Point(this.x, this.y);

    }// end function

    public function updateRotation():void {


        this.rotation = getAngle();

    }// end function

    public function getAngle():Number {

        var dPoint:Point = getDPoint();
        return Math.atan2(dPoint.y, dPoint.x) * (180 / Math.PI) + 90;

    }// end function

}// end class

Trying running it, and see if it's along the line of what you needed. If so, I'll explain the example in steps.

Here's a screenshot of the example application running:

enter image description here

[UPDATE]

@Siva I just added the public rotate() method and the private onRotationEnterframe event handler.

The rotate() method simply adds an Event.ENTER_FRAME listener to the NPC object.

public function rotate():void {

    this.addEventListener(Event.ENTER_FRAME, onRotationEnterFrame);

}// end function

When the onRotationEnterFrame() event handler is called, the first statement gets the difference between the angle the NPC object will rotate to and the NPC object's current angle.

var dAngle:int = (getAngle() - this.rotation) % 360;

Depending on if the angle is less than -180 degrees or greater than 180 degrees, we add or subtract 360 degrees.

        if (dAngle < -180) {

            dAngle += 360;

        }
        else if (dAngle > 180) {

            dAngle -= 360;

        }// end if

We then use the altered angle to work out whether we rotate clockwise or anti clockwise.

        if (dAngle < 0) {

            --this.rotation;

        } else { 

            ++this.rotation;

        }// end if

When the angle reaches 0 we remove the onRotationEnterFrame event listener and dispatch a NPC.ROTATION_COMPLETE event.

        if (dAngle == 0) {

            removeEventListener(Event.ENTER_FRAME, onRotationEnterFrame);
            dispatchEvent(new Event(NPC.ROTATION_COMPLETE));

        }// end if

Finally on the client side, we alter the onMoveComplete() event handler by adding an event listener that listens for NPC.ROTATION_COMPLETE. We set the new points for the new line that the NPC object will follow, then call the NPC object's rotate().

Upvotes: 2

Related Questions