Rotating Sprite

I have a sprite on stage that I want to rotate, The sprite itself contains a shape (a triangle) with these coordinates (10,10)(10,50)(20,30).
When I rotate the sprite (as it is now) using spritename.rotate=nn, it rotates, but around the (0,0) position of the parent container (a movieclip). In an attempt to figure out what was going on, I set up some trace statements, including one to check the width and height of the sprite. It changes with each rotation.
Not sure what is going on here, or why the sprite rotates using the parent mc, but if someone could point me in the right direction, I would appreciate it.

use:
var sp:Sprite = new Sprite();
with(sp.graphics){
    beginFill(0xaa0000);
    moveTo(0,0);
    lineTo(0,40);
    lineTo(10,20);
    lineTo(0,0);
sp.x = -sp.width/2;
sp.y = -sp.height/2;
var p:Sprite = new Sprite();
p.addChild(sp);
p.x = 10+p.width/2;
p.y = 10+p.height/2;
addChild(p);
now p will act like your sprite with its reg point changed to the center.  just rotate and otherwise manipulate p instead of sp.

Similar Messages

  • Rotating Sprite Center Axis

    Hi,
    I found an interesting tutorial (link) and created a working model, adapting it as needed.
    So far, when I center the container sprite and rotate it, it appears to first rotate from a 0,0 registration point, instead of from its center. I've tried to changet he sprite's registration point, but so far this hasn't worked/helped. Nothing else has worked to fix this rotation problem.
    I must be doing something wrong.
    Here's the AS3 (to view, add to first frame of new FLA, 1024X768 stage, color black). Rotation segments below are commented as       //ROTATION.:
    import flash.display.Sprite;
        import flash.events.MouseEvent;
        import flash.events.Event;
        import flash.text.TextField;
        //import flash.geom.ColorTransform;
    stop();
        //public class bejewelled extends Sprite {
            var gems_array:Array=new Array();
            var aGem:Sprite;
            var selectorBox:Sprite=new Sprite();
            var selectorRow:int=-10;
            var selectorColumn:int=-10;
            var red:uint = 0xFF0000;
            var green:uint = 0xFF00;
            var blue:uint = 0xFF;
            var yellow:uint = 0xFFFF00;
            var cyan:uint = 0xFFFF;
            var magenta:uint = 0xFF00FF;
            var white:uint = 0xFFFFFF;
            var colours_array:Array=new Array(red,green,blue,yellow,cyan,magenta,white);
            var clickPossible:Boolean=false;
            var score_txt:TextField=new TextField();
            var hint_txt:TextField=new TextField();
            var score:uint=0;
            var inaRow:uint=0;
            var match:Boolean = true;
            var gemSize:uint = 96;
            var format:TextFormat = new TextFormat();
            var rotate:Boolean=false;
            var container:Sprite = new Sprite(); // Create the container sprite
             //var newColorTransform:ColorTransform = exitBtn.transform.colorTransform;
            //newColorTransform.color = 0xff0000;
            //exitBtn.transform.colorTransform = newColorTransform;
            function bejewelled() {
                // Game initiation
                format.size = 40;
                format.font = 'Arial';
                // Create and style score text
                addChild(score_txt);
                score_txt.textColor=0xFFFFFF;
                score_txt.x=gemSize*9.6;
                score_txt.autoSize = TextFieldAutoSize.LEFT;
                score_txt.defaultTextFormat = format;           
                // Create and style hint text
                addChild(hint_txt);
                hint_txt.textColor=0xFFFFFF;
                hint_txt.x=gemSize*9.6;
                hint_txt.y=gemSize;
                hint_txt.autoSize = TextFieldAutoSize.LEFT;
                hint_txt.defaultTextFormat = format;
                // Create Gems in rows and columns
                addChild(container); // Add the container to the display list (stage)
                for (var i:uint=0; i<8; i++) {
                    gems_array[i]=new Array();
                    for (var j:uint=0; j<8; j++) {
                        do {
                            gems_array[i][j]=Math.floor(Math.random()*7);
                            while (rowLineLength(i,j)>2 || columnLineLength(i,j)>2);
                        aGem=new Sprite();
                        aGem.graphics.beginFill(colours_array[gems_array[i][j]]);
                        aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
                        aGem.graphics.endFill();
                        aGem.name=i+"_"+j;
                        aGem.x=j*gemSize;
                        aGem.y=i*gemSize;
                        container.addChild(aGem);
                //Center the container sprite
                container.width = container.width - 10;
                container.height =  container.height - 10;           
                container.x = (stage.stageWidth-container.width)/2;
                container.y = (stage.stageHeight-container.height)/2;
                // Create and style selector box
                container.addChild(selectorBox);
                selectorBox.graphics.lineStyle(2,red,1);
                selectorBox.graphics.drawRect(0,0,gemSize,gemSize);
                selectorBox.visible=false;
                // Listen for user input
                container.addEventListener(MouseEvent.CLICK,onClick);
                addEventListener(Event.ENTER_FRAME,everyFrame);
            // Every frame...
            function everyFrame(e:Event):void {
                //Assume that gems are not falling
                var gemsAreFalling:Boolean=false;
                // Check each gem for space below it
                for (var i:int=6; i>=0; i--) {
                    for (var j:uint=0; j<8; j++) {
                        // If a spot contains a gem, and has an empty space below...
                        if (gems_array[i][j] != -1 && gems_array[i+1][j]==-1) {
                            // Set gems falling
                            gemsAreFalling=true;
                            gems_array[i+1][j]=gems_array[i][j];
                            gems_array[i][j]=-1;
                            trace("#");
                            trace(i+"_"+j);
                            container.getChildByName(i+"_"+j).y+=gemSize;
                            container.getChildByName(i+"_"+j).name=(i+1)+"_"+j;
                            break;
                    // If a gem is falling
                    if (gemsAreFalling) {
                        // don't allow any more to start falling
                        break;
                // If no gems are falling
                if (! gemsAreFalling) {
                    // Assume no new gems are needed
                    var needNewGem:Boolean=false;
                    // but check all spaces...
                    for (i=7; i>=0; i--) {
                        for (j=0; j<8; j++) {
                            // and if a spot is empty
                            if (gems_array[i][j]==-1) {
                                // now we know we need a new gem
                                needNewGem=true;
                                // pick a random color for the gem
                                gems_array[0][j]=Math.floor(Math.random()*7);
                                // create the gem
                                aGem=new Sprite();
                                aGem.graphics.beginFill(colours_array[gems_array[0][j]]);
                                aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
                                aGem.graphics.endFill();
                                // ID it
                                aGem.name="0_"+j;
                                // position it
                                aGem.x=j*gemSize;
                                aGem.y=0;
                                // show it
                                container.addChild(aGem);
                                // stop creating new gems
                                break;
                        // if a new gem was created, stop checking
                        if (needNewGem) {
                            break;
                    // If no new gems were needed...
                    if (! needNewGem) {
                        // assume no more/new lines are on the board
                        var moreLinesAvailable:Boolean=false;
                        // check all gems
                        for (i=7; i>=0; i--) {
                            for (j=0; j<8; j++) {
                                // if a line is found
                                if (rowLineLength(i,j)>2 || columnLineLength(i,j)>2) {
                                    // then we know more lines are available
                                    moreLinesAvailable=true;
                                    // creat a new array, set the gem type of the line, and where it is
                                    var lineGems:Array=[i+"_"+j];
                                    var gemType:uint=gems_array[i][j];
                                    var linePosition:int;
                                    // check t's a horizontal line...
                                    if (rowLineLength(i,j)>2) {
                                        // if so, find our how long it is and put all the line's gems into the array
                                        linePosition=j;
                                        while (sameGemIsHere(gemType,i,linePosition-1)) {
                                            linePosition--;
                                            lineGems.push(i+"_"+linePosition);
                                        linePosition=j;
                                        while (sameGemIsHere(gemType,i,linePosition+1)) {
                                            linePosition++;
                                            lineGems.push(i+"_"+linePosition);
                                    // check t's a vertical line...
                                    if (columnLineLength(i,j)>2) {
                                        // if so, find our how long it is and put all the line's gems into the array
                                        linePosition=i;
                                        while (sameGemIsHere(gemType,linePosition-1,j)) {
                                            linePosition--;
                                            lineGems.push(linePosition+"_"+j);
                                        linePosition=i;
                                        while (sameGemIsHere(gemType,linePosition+1,j)) {
                                            linePosition++;
                                            lineGems.push(linePosition+"_"+j);
                                    // for all gems in the line...
                                    for (i=0; i<lineGems.length; i++) {
                                        // remove it from the program
                                        container.removeChild(container.getChildByName(lineGems[i]));
                                        // find where it was in the array
                                        var cd:Array=lineGems[i].split("_");
                                        // set it to an empty gem space
                                        gems_array[cd[0]][cd[1]]=-1;
                                        // set the new score
                                        score+=inaRow;
                                        // set the score setter up
                                        inaRow++;
                                    // if a row was made, stop the loop
                                    break;
                            // if a line was made, stop making more lines
                            if (moreLinesAvailable) {
                                break;
                        // if no more lines were available...
                        //ROTATION
                        if (! moreLinesAvailable) {
                            if(rotate){
                                container.rotation+=5;                           
                                if(container.rotation%90==0){
                                    rotate=false;
                                    container.rotation=0;
                                    rotateClockwise(gems_array);
                                    while(container.numChildren>0){
                                        container.removeChildAt(0);
                                    for (i=0; i<8; i++) {
                                        for (j=0; j<8; j++) {
                                            aGem=new Sprite();
                                            aGem.graphics.beginFill(colours_array[gems_array[i][j]]);
                                            aGem.graphics.drawCircle(gemSize/2,gemSize/2,gemSize/2.07);
                                            aGem.graphics.endFill();
                                            aGem.name=i+"_"+j;
                                            aGem.x=j*gemSize;
                                            aGem.y=i*gemSize;
                                            container.addChild(aGem);                                       
                                            container.addChild(selectorBox);
                                            selectorBox.graphics.lineStyle(2,red,1);
                                            selectorBox.graphics.drawRect(0,0,gemSize,gemSize);
                                            selectorBox.visible=false;
                            else{
                                // allow new moves to be made
                                clickPossible=true;
                                // remove score multiplier
                                inaRow=0;
                // display new score
                score_txt.text=score.toString();
            // When the user clicks
            function onClick(e:MouseEvent):void {
                // If a click is allowed
                if (clickPossible) {
                    // If the click is within the game area...
                    if (mouseX<container.x+gemSize*8 && mouseX>0 && mouseY<container.y+gemSize*8 && mouseY>0) {
                        // Find which row and column were clicked
                        var clickedRow:uint=Math.floor((mouseY-container.y)/gemSize);
                        //var clickedRow:uint=Math.floor(e.target.y/gemSize);
                        var clickedColumn:uint=Math.floor((mouseX-container.x)/gemSize);
                        //var clickedColumn:uint=Math.floor(e.target.x/gemSize);
                        // Check if the clicked gem is adjacent to the selector
                        // If not...
                        if (!(((clickedRow==selectorRow+1 || clickedRow==selectorRow-1)&&clickedColumn==selectorColumn)||((clickedColumn==selectorColumn+1 || clickedColumn==selectorColumn-1) && clickedRow==selectorRow))) {
                            // Find row and colum the selector should move to
                            selectorRow=clickedRow;
                            selectorColumn=clickedColumn;
                            // Move it to the chosen position
                            selectorBox.x=gemSize*selectorColumn;
                            selectorBox.y=gemSize*selectorRow;
                            // If hidden, show it.
                            selectorBox.visible=true;
                        // If it is not next to it...
                        else {
                            // Swap the gems;
                            swapGems(selectorRow,selectorColumn,clickedRow,clickedColumn);
                            // If they make a line...
                            if (rowLineLength(selectorRow,selectorColumn)>2 || columnLineLength(selectorRow,selectorColumn)>2||rowLineLength(clickedRow,clickedColumn)>2 || columnLineLength(clickedRow,clickedColumn)>2) {
                                // remove the hint text
                                hint_txt.text="";
                                // dis-allow a new move until cascade has ended (removes glitches)
                                clickPossible=false;
                                // move and rename the gems
                                container.getChildByName(selectorRow+"_"+selectorColumn).x=e.target.x;//clickedColumn*gemSize;
                                container.getChildByName(selectorRow+"_"+selectorColumn).y=e.target.y;//clickedRow*gemSize;
                                container.getChildByName(selectorRow+"_"+selectorColumn).name="t";
                                container.getChildByName(clickedRow+"_"+clickedColumn).x=selectorColumn*gemSize;
                                container.getChildByName(clickedRow+"_"+clickedColumn).y=selectorRow*gemSize;
                                container.getChildByName(clickedRow+"_"+clickedColumn).name=selectorRow+"_"+selectorColumn;
                                container.getChildByName("t").name=clickedRow+"_"+clickedColumn;
                                match = true;
                                rotate = true;
                            // If not...
                            else {
                                // Switch them back
                                swapGems(selectorRow,selectorColumn,clickedRow,clickedColumn);
                                match = false;
                            if (match) {
                                // Move the selector position to default
                                selectorRow=-10;
                                selectorColumn=-10;
                                // and hide it
                                selectorBox.visible=false;
                            else {
                                // Set the selector position
                                selectorRow=clickedRow;
                                selectorColumn=clickedColumn;
                                // Move the box into position
                                selectorBox.x=gemSize*selectorColumn;
                                selectorBox.y=gemSize*selectorRow;
                                match = false;
                                // If hidden, show it.
                                selectorBox.visible=true;
                    // If the click is outside the game area
                    else {
                        // For gems in all rows...
                        for (var i:uint=0; i<8; i++) {
                            // and columns...
                            for (var j:uint=0; j<8; j++) {
                                // if they're not too close to the side...
                                if (i<7) {
                                    // swap them horizontally
                                    swapGems(i,j,i+1,j);
                                    // check if they form a line
                                    if ((rowLineLength(i,j)>2||columnLineLength(i,j)>2||rowLineLength(i+1,j)>2||columnLineLength(i+1,j)>2)) {
                                        // if so, name the move made
                                        selectorBox.x = j*gemSize;
                                        selectorBox.y = i*gemSize;
                                        selectorBox.visible = true;
                                        hint_txt.text = (i+1).toString()+","+(j+1).toString()+"->"+(i+2).toString()+","+(j+1).toString();
                                    // swap the gems back
                                    swapGems(i,j,i+1,j);
                                // then if they're not to close to the bottom...
                                if (j<7) {
                                    // swap it vertically
                                    swapGems(i,j,i,j+1);
                                    // check if it forms a line
                                    if ((rowLineLength(i,j)>2||columnLineLength(i,j)>2||rowLineLength(i,j+1)>2||columnLineLength(i,j+1)>2) ) {
                                        // if so, name it
                                        selectorBox.x = j*gemSize;
                                        selectorBox.y = i*gemSize;
                                        selectorBox.visible = true;
                                        hint_txt.text = (i+1).toString()+","+(j+1).toString()+"->"+(i+1).toString()+","+(j+2).toString();
                                    // swap the gems back
                                    swapGems(i,j,i,j+1);
            //Swap given gems
            function swapGems(fromRow:uint,fromColumn:uint,toRow:uint,toColumn:uint):void {
                //Save the original position
                var originalPosition:uint=gems_array[fromRow][fromColumn];
                //Move original gem to new position
                gems_array[fromRow][fromColumn]=gems_array[toRow][toColumn];
                //move second gem to saved, original gem's position
                gems_array[toRow][toColumn]=originalPosition;
            //Find out if there us a horizontal line
            function rowLineLength(row:uint,column:uint):uint {
                var gemType:uint=gems_array[row][column];
                var lineLength:uint=1;
                var checkColumn:int=column;
                //check how far left it extends
                while (sameGemIsHere(gemType,row,checkColumn-1)) {
                    checkColumn--;
                    lineLength++;
                checkColumn=column;
                //check how far right it extends
                while (sameGemIsHere(gemType,row,checkColumn+1)) {
                    checkColumn++;
                    lineLength++;
                // return total line length
                return (lineLength);
            //Find out if there us a vertical line
            function columnLineLength(row:uint,column:uint):uint {
                var gemType:uint=gems_array[row][column];
                var lineLength:uint=1;
                var checkRow:int=row;
                //check how low it extends
                while (sameGemIsHere(gemType,checkRow-1,column)) {
                    checkRow--;
                    lineLength++;
                //check how high it extends
                checkRow=row;
                while (sameGemIsHere(gemType,checkRow+1,column)) {
                    checkRow++;
                    lineLength++;
                // return total line length
                return (lineLength);
            function sameGemIsHere(gemType:uint,row:int,column:int):Boolean {
                //Check there are gems in the chosen row
                if (gems_array[row]==null) {
                    return false;
                //If there are, check if there is a gem in the chosen slot
                if (gems_array[row][column]==null) {
                    return false;
                //If there is, check if it's the same as the chosen gem type
                return gemType==gems_array[row][column];
               //ROTATION
               function rotateClockwise(a:Array):void {
                var n:int=a.length;
                for (var i:int=0; i<n/2; i++) {
                    for (var j:int=i; j<n-i-1; j++) {
                        var tmp:String=a[i][j];
                        a[i][j]=a[n-j-1][i];
                        a[n-j-1][i]=a[n-i-1][n-j-1];
                        a[n-i-1][n-j-1]=a[j][n-i-1];
                        a[j][n-i-1]=tmp;
    bejewelled();  
    Any help appreciated.

    OK, way too much code. By default, everything will rotate from top left. If you want to change that you need to change the positions of the content within the container, not the container itself.
    For example if you do something like this:
    var a:Sprite = new Sprite(); //container
    addChild(a);
    a.x = 100; a.y = 100;
    var b:MovieClip = new car(); //clip from library
    a.addChild(b);
    addEventListener(Event.ENTER_FRAME, up);
    function up(e:Event):void
              a.rotation += 1;
    The car added to the container will rotate about it's top left point... because that's where the container rotates about. To fix, move the car so the containers top/left is at the car's center like so:
    var a:Sprite = new Sprite();
    addChild(a);
    a.x = 100; a.y = 100;
    var b:MovieClip = new car();
    a.addChild(b);
    b.x -= b.width / 2;
    b.y -= b.height / 2;
    addEventListener(Event.ENTER_FRAME, up);
    function up(e:Event):void
              a.rotation += 1;
    You'll notice all that changed is moving the car 1/2 it's width and height.
    HTH

  • Constrain To Sprite doesn't like rotating sprites...

    I have a bunch of movable sprites that I'd like to constrain
    to a box
    (basically just the whole stage). Problem is that they also
    have the
    ability to rotate, only at 90 degree intervals, though.
    They're relatively
    rectangular shapes (puzzle pieces). But when you rotate them
    with the
    Constrain to Sprite behavior on them, their aspect ratio gets
    all screwed
    up, and then sometimes they start moving on their own until
    they hit an
    edge, quite odd behavior. Is there a way to make this
    behavior work with
    sprites that can be rotated without these glitches? Or is
    there a better
    alternative? I tried writing my own contstrain script, which
    worked except
    that you could still drag the sprites off the edge, they'd
    just keep
    bouncing back and forth until you released the mouse button.
    Also not good
    behavior.

    Are you dragging these sprites around or are you moving them
    in some
    other way?
    If you are dragging the sprites around then you can use
    sprite(X).within(Y) to keep your sprites from leaving the
    stage area.
    1. Make a borderless empty toolbox shape sprite that is
    slightly smaller
    than the whole stage. Make is sprite 1.
    2. constrain each sprite to that sprite.
    3. use a simple behavior like this to control the moving of
    each sprite:
    property thisSprite
    property animateMe
    on beginSprite me
    thisSprite = me.spriteNum
    animateMe = false
    sprite(thisSprite).constraint = 1
    end
    on mouseDown me
    animateMe = true
    end
    on mouseUp me
    animateMe = false
    end
    on exitFrame me
    if animateMe then
    sprite(thisSprite).loc = the mouseLoc
    end if
    end
    Rob
    Rob Dillon
    Adobe Community Expert
    http://www.ddg-designs.com
    412-243-9119
    http://www.macromedia.com/software/trial/

  • Sprites don't rotate on certain computer

    This is really bizarre! I have a game that has fish falling
    from the sky. These fish rotate as they are falling. Everything
    works fine on 5 computers. I just tested the game on another
    computer and the sprites do not rotate as they fall. I am at a
    total loss on this one and have no idea what could cause this or
    what a potential solution might be. Here is the simple code and the
    specs of the computer that it's failing on...
    I've tried it both ways below with similar results... (no
    rotation)
    repeat with t = pUsingSprites.count down to 1
    s = pUsingSprites[t]
    sprite(s).rotation = integer(sprite(s).rotation + 2) mod 360
    end repeat
    repeat with t = pUsingSprites.count down to 1
    s = pUsingSprites[t]
    sprite(s).rotation = sprite(s).rotation + 10
    end repeat
    The specs for the offending computer are...
    AMD 64 X2 4800+
    Geforce6100SM-M motherboard
    onboard 6100 geforce video
    1 GB RAM
    Realtek onboard audio
    Windows XP with Service Pack 2
    What could cause one computer with same OS to not rotate fish
    while all other computers do rotate the fish?
    Thanks!

    iTunes: Finding lost media and downloads

  • Method of MatrixTransformer not defined?

    hi, everyone.
    when I use MatirxTransformer to rotate sprite, occure an
    error:
    1061: Call to a possibly undefined method getRotation through
    a reference with static type fl.motion:MatrixTransformer.
    then I try another method of it, same error occured.
    All method of MatirxTransformer not definded?
    thanks.

    sorry, I got it.
    I don't notice MatirxTransformer is a static type.

  • [svn] 4335: GraphicElement Optimization

    Revision: 4335
    Author: [email protected]
    Date: 2008-12-16 16:52:56 -0800 (Tue, 16 Dec 2008)
    Log Message:
    GraphicElement Optimization
    - Changed how a shared displayObject is positioned in a GraphicElement. Previously, it was always placed at (x,y). Now, it is placed at (0,0) if the displayObject can be shared (ie. it has no transforms). This solves the problem of a sharedDisplayObject getting repositioned without the GraphicElement being aware of it.
    - Optimized Group.updateDisplayList so that we only redraw the GraphicElement's that share a displayObject that needs to be updated. Added a new class called InvalidatingSprite which has a single property called "invalid". If a GraphicElement needs to be redrawn, it marks its shared or unshared displayObject as invalid. Group will then only update the GraphicElements whose displayObject is marked invalid. Added invalidateDisplayList calls in a few missing places.
    QE Notes: Some of the mustella bitmaps need to be regenerated. The player renders differently two transformed sprites that draw the same visuals. For example, a rotated sprite at (0,0) with a drawRect at (20,20) will look from a rotated sprite at (20,20) with a drawRect at (0,0).
    Doc Notes: None
    Bugs: SDK-18053
    Reviewer: Evtim
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-18053
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/Group.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/baseClasses/FxTrackBase.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/Line.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/Path.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/graphicsClasses/GraphicElement.a s
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/skins/spark/FxVSliderSkin.mxml
    Added Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/core/InvalidatingSprite.as

  • Im trying to create a "wobbling" effect with a bitmap

    im trying to create a "wobbling" effect with a bitmap
    any idea how to go with this with director?

    It somewhat depends on what the effect is intended to acheive.
    Here is a simple behavior script that can be applied to any bitmap. It wobbles, in the sense that it has a radom movement about its axis.
    That is acheived with the random() statements. The amount of wobble can be controlled by changing the value added to each parameter on each iteration.
    The last three statements keep the wobble from randomly walking off the frame. Again, wobble can be changed by setting the corrective value at which point the bitmap returns to its original state.
    Hope this helps.
    property spritenum
    global glocH, gLocV, gRotation
    On beginsprite
      gloch = sprite(spritenum).loch
      gloch = sprite(spritenum).locv
      gRotation = integer(sprite(spritenum).Rotation)
    end
    On enterframe
    b = random(2)
      if b=1 then
        sprite(spritenum).loch = sprite(spritenum).loch + random(2)
      else
        sprite(spritenum).loch = sprite(spritenum).loch - random(2)
      end if
      c= random(2)
      if c=1 then
        sprite(spritenum).locv = sprite(spritenum).locV + random(2)
      else
        sprite(spritenum).locv = sprite(spritenum).locV - random(2)
      end if
      d= random(2)
      if d=1 then
        Sprite(spritenum).rotation = sprite(spritenum).rotation + random(4)
      else
        Sprite(spritenum).rotation = sprite(spritenum).rotation - random(4)
      end if
    if abs(gloch + sprite(spritenum).loch) <= 8  then sprite(spritenum).loch = gloch
    if abs(glocv + sprite(spritenum).locv) <= 8 then sprite(spritenum).locv = glocv
    if abs(Integer(gRotation - sprite(spritenum).Rotation)) >=8 then sprite(spritenum).rotation = gRotation
    end

  • Tank movement?

    Ok, I have looked at everything and I have had several other people try and help me but I can not figure this out. My tanks rotation just isn't working right.      
            public void setVector()
                        //setting my degree measurement using my array of  ints that represent my movement keys in ascii               
             baseTheta+=(controls[68]-controls[65]);
             //setting my magnitude
                incMove=controls[87]-controls[83];
                //setting my vector
             direction.set(incMove,Math.toRadians(baseTheta));     
         }I control the tank with a simple vector class(my instance of it is direction), that takes the sin and cos to determine the x and y.
         public void set(double magnitude, double angle)
              setX(magnitude * Math.cos(angle));
              setY(magnitude * Math.sin(angle));
         }Now, I have a thread that constantly calls the move method, which just incriments the x and y. My paint draw method within my tank class contains this
         g2.setTransform(identity);
         g2.translate(basePos.x,basePos.y);
         g2.scale(baseScale,baseScale);
         g2.rotate(Math.toRadians(baseTheta));
         g2.setColor(baseColor);
         g2.fill(baseShape);And so I just have it increment the x and y and then rotate it with the same variable, This seems to work except for a small problem. When you move backwards(which will make the magnitude a -10) and it has the same angle value as it was going forward, the images angle doesnt chang and is correct, but my X and Y are incrimented wrong. So if im going at an angle of say 30 degrees and moving forward it works fine. But when I move backwards my angle for rotation is correct and doesnt change, but my X and Y is out of wack and it doesnt move in the correct direction.

    here you go. this should help you.
    import java.awt.*;
    import java.util.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.net.*;
    import java.io.*;
    public class SpriteExample extends Applet implements Runnable, KeyListener{
         Graphics2D dbg;
         Image dbImage;
         public int gameSpeed = 100;
         public int numOfImages = 2;
         Thread th;
         boolean forward=false, reverse=false, left=false,right=false;
         Sprite[] sprite = new Sprite[numOfImages];
         public void init(){
              setSize(500,500);
              setBackground(Color.black);
              addKeyListener(this);
              Image image = getImage(getCodeBase(),"image.jpg");
              for(int a=0;a<numOfImages;a++){
                   sprite[a]=new Sprite(image, new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255)), new Point((int)(Math.random()*500),(int)(Math.random()*500)), Math.random()*360,Math.random()*12-6);
         public void start (){
              th = new Thread (this);
              th.start ();
         public void run ()     {
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              while (true){
                   checkControls();
                   for(int i=0;i<numOfImages;i++){
                        sprite.move();
                   repaint();
                   try     {
                        th.sleep (gameSpeed);
                   }catch (InterruptedException ex){
         public void paint (Graphics2D g)     {
              for(int a=0;a<numOfImages;a++){
                   sprite[a].draw(g);
                   g.setColor(Color.black);
         public void update (Graphics g)     {
              if (dbImage == null){
                   dbImage = createImage (this.getSize().width, this.getSize().height);
                   dbg = (Graphics2D)dbImage.getGraphics();
              dbg.setColor (getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (getForeground());
              paint (dbg);
              g.drawImage (dbImage, 0, 0, this);
         public void keyPressed(KeyEvent e) {
              if (e.getKeyCode()==61){sprite[0].Rotation=sprite[0].Rotation+5;}
              if (e.getKeyCode()==45){sprite[0].Rotation=sprite[0].Rotation-5;}
              if (e.getKeyCode()==38){forward=true;}else
              if (e.getKeyCode()==40){reverse=true;}else
              if (e.getKeyCode()==37){left=true;}else
              if (e.getKeyCode()==39){right=true;}
         public void keyReleased(KeyEvent e) {
              if (e.getKeyCode()==38){forward=false;}else
              if (e.getKeyCode()==40){reverse=false;}else
              if (e.getKeyCode()==37){left=false;}else
              if (e.getKeyCode()==39){right=false;}
         public void keyTyped(KeyEvent e) {}
         public void checkControls(){
              for(int a=0;a<numOfImages;a++){
              if (forward){sprite[a].accel() ;}
              if (reverse){sprite[a].deccel() ;}
              if (left) {sprite[a].turnLeft() ;}
              if (right) {sprite[a].turnRight();}
    class Sprite extends Object {
         private Image image;
         AffineTransform imageLocation=new AffineTransform();
         double velocity;
         Rectangle bounds;
         Rectangle refShape=new Rectangle(32,32);
         double MaxSpeed=6;
         double AccelRate=.3;
         public double Rotation=6;
         double posX,posY,angle;
         Color boxColor;
         public boolean keyDown = false;
         double dx,dy;
         public Sprite(Image img, Color color, Point location, double ang, double speed){
              posX=location.x;          posY=location.y;          boxColor = color;
              image=img;                    velocity=speed;               angle=ang;
              bounds=new Rectangle((int)posX,(int)posY,32,32);
         public void draw(Graphics2D g){
              g.setColor(boxColor);
              g.fill(bounds);
              g.setColor(Color.black);
              g.drawImage(image,imageLocation,null);
         public void setLocation(Point point) {posX=point.x; posY=point.y; }
         public Point getLocation() {return bounds.getLocation();}
         public void setBounds(Rectangle rect){bounds=rect;                }
         public Rectangle getBounds() {return bounds;              }
         public void setSpeed(double speed) {velocity=speed;                 }
         public double getSpeed() {return velocity;            }
         public void setAngle(double theta) {angle=theta;                }
         public double getAngle() {return angle;               }
         public void turnLeft() {angle=angle-Rotation;       }
         public void turnRight() {angle=angle+Rotation;       }
         public AffineTransform getForm() {return imageLocation;          }
         public void setForm(AffineTransform xform){                       }
         public void accel(){if(velocity<MaxSpeed){velocity=velocity+AccelRate;}}
         public void deccel(){if(velocity> -MaxSpeed){velocity=velocity-AccelRate;}}
         public void move(){
              dx=Math.cos(Math.toRadians(angle))*velocity;
              dy=Math.sin(Math.toRadians(angle))*velocity;
              posX=posX+dx;
              posY=posY+dy;
              imageLocation=AffineTransform.getTranslateInstance(posX,posY);
              imageLocation.rotate(Math.toRadians(angle)+Math.PI/2,16,16);
              bounds.setLocation((int)posX,(int)posY);
              if(!keyDown){
                   if (velocity<0){velocity=velocity+.15;}else if (velocity>0){velocity=velocity - 0.15;}

  • IOS 6: problem with sprites rotation in gpu mode

    Hi,
    I have a game published on iTunes and today I found a serious problem with the latest iOS 6 GM.
    Sprite rotation around X and Y axes doesn't work with gpu render mode.
    Here is my code:
    <mx:UIComponent id="gameCanvas" mouseChildren="false" mouseEnabled="false" width="100%" height="100%" />
    var gridSprite:Sprite=new Sprite();
    gameCanvas.addChildAt(gridSprite,0);
    // then I draw stuff on this gridSprite
    It works fine if this sprite is not rotated.
    But when I change its rotationX or rotationY properties, the sprite disappears from the screen!
    My game works fine on older versions of iOS (5.0, 5.1.1 and 6 beta 3).
    This problem only happens on iOS 6 GM and since iOS 6 will be officially released in a few days, I am really worried...
    I tried Air 3.3 and Air 3.4 - both have this problem.
    In "cpu" and "direct" render modes sprite rotation works, but graphics performance is terrible. So "gpu" is my only option...
    I'll really appreciate any help.

    I performed some other tests and so it seems like everything is 2D in gpu mode. When I try to do 3D transformations, objects disappear from the view.
    For example out of these 3 images only image1 is displayed:
    <s:BitmapImage id="image1"  source="logo.png" height="25%" width="100%" />
    <s:BitmapImage id="image2"  source="logo.png" height="25%" width="100%"  rotationY="5"/>
    <s:BitmapImage id="image3"  source="logo.png" height="25%" width="100%"  z="5"/>
    Maybe there is some setting that enables 3D (something like zBufferEnabled=true) that needs to be explicitly set for iOS 6 in gpu mode?
    UPD: Ok, I'm pretty sure it's a bug, I reported it to Adobe - Bug 3330901

  • 359 Degree Sprite Rotation Crashes App

    This is a weird bug I've been chasing for a while with
    spontaneous crashing of a Director App in OSX. I've now narrowed it
    down to when I rotate a sprite to 359 degrees. It only occurs at
    higher resolutions ( ie. 1680 x 1050 ). At lower resolutions it is
    quite stable. I can move and scale the sprite as much as I like. I
    can rotate it to any other angle but 359 degrees crashes my
    application.
    Anyone seen anything like this?
    The crash log refers to EXC_BAD_ACCESS/ KERN_INVALID_ADDRESS
    in unknown thread if that means anything to anyone.
    Edit:
    It seems the sprite's flips affect the angle.
    flipH = FALSE, flipV = FALSE, crash at 359 degrees
    flipH = FALSE, flipV = TRUE, crash at 1 degree
    flipH = TRUE, flipV = FALSE, crash at 181 degrees
    flipH = TRUE, flipV = TRUE, crash at 179 degrees

    I guess I'm talking to myself here but I have also found that
    it only occurs when the image is scaled up. If I use a larger image
    and scale it down then rotation isn't an issue.
    So to summarise the issue;
    - authored at 1024 x 768 projector running full screen at
    1680 x 1050
    - small image ( 1000 x 750 ) linked dynamically and scaled
    proportionately to almost fill screen ( scaling down or
    disproportionately doesn't crash )
    - sprite rotated to 359 degrees ( with no h or v flips )
    - app crashes ( also crashes Director when I run it full
    screen in authoring )

  • Rotate 3D sprites to point at the camera

    Hi all,
    I'm in the middle of creating a scene where a camera (on a path) passes several 3D layers. On the 3D sprites is a .png mapped of a figure. Is there a simple way to make the 3D layers automatically rotate around their Y-axis so the mapped figures appear to be looking at the camera while it passes by ? It seems a huge work to achieve this by manually adjusting the parameters of the layers...
    Thanks in advance for the reply!
    Sven
    ps: using After Effects CS3, CS4 is at my disposal if needed.

    You can auto-orient layers in all 3 dimensions using Layer/Transform/Auto-Orient.
    To limit it to the Y axis, look at Dan Ebbert's expression on his website:
    http://www.motionscript.com/design-guide/auto-orient-y-only.html

  • Sprite rotation... help someone just entering the fray of java 2D!

    Okay, so I'm basically having a crash course in the usage of sprites, and it seems to me the easiest way to rotate them is via AffineTransform.
    Now, from what I understand, this is used to rotate an entire graphics context, but I don't want to rotate the entire thing, just a ball. Now to do this, I either need another method, or a way to draw a graphics context on another one, that is, have a ball be the entirety of a graphics context, and draw that on top of the graphics context I already have. Any help on performing this last action would be cool, or if anyone had a better suggestion, I would enjoy that as well.

    This might help
    package forums;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import java.awt.Font;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GradientPaint;
    import java.awt.RenderingHints;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.geom.AffineTransform;
    import com.sun.awt.AWTUtilities;
    public class SplashPortalPanel5 extends JPanel
        private static final long serialVersionUID = 1L;
        private static final char[] MESSAGE = "  SplashPortal.net".toCharArray();
        private static final double R90 = Math.toRadians(90);
        private static final double R_90 = Math.toRadians(-90);
        private AffineTransform cumalativeRotation = new AffineTransform();
        private double rotation = Math.toRadians(360.0 / MESSAGE.length);
        private Font font = new Font("Impact",Font.ITALIC,40);
        private final Timer timer = new Timer(1000/76, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                repaint();//just repaint
        public SplashPortalPanel5() {
          setPreferredSize(new java.awt.Dimension(600, 600));
          setOpaque(false);
        //This method is called when the panel is connected to a native
        //screen resource.  It's an indication we can now start painting.
        public void addNotify() {
            super.addNotify();
            timer.start();
        public void removeNotify() {
            super.removeNotify();
            timer.stop();
        private static final GradientPaint gradient = new GradientPaint(0F, 0F, Color.BLUE, 5F, 10F, Color.CYAN, true);
        private static final int x = 0, y = 0, w = 100, h = 100;
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setFont(font);
            g2.translate( getWidth()/2, getHeight()/2 );
            cumalativeRotation.rotate(rotation/50);
            g2.transform( cumalativeRotation );
            for(int i = 0; i < MESSAGE.length; i++) {
                // fill the rectangle
                g2.translate(250, 0);
                g2.rotate(R90);
                g2.setColor(Color.BLACK);
                g2.fillRect(x,y,w,h);
                // draw the border
                g2.setColor(Color.WHITE);
                g2.drawRect(x,y,w,h);
                // draw the character
                g2.setPaint(gradient);
                g2.drawChars(MESSAGE,i, 1, x+30, y+50);
                g2.rotate(R_90);
                g2.translate(-250, 0);
                g2.rotate(rotation);
        public static void createAndShowSplashScreen() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setUndecorated(true);
            frame.setContentPane(new SplashPortalPanel5());
            frame.pack();
            frame.setLocationRelativeTo(null);
            AWTUtilities.setWindowOpaque(frame, false);
            //frame.setAlwaysOnTop(true);
            frame.setVisible(true);
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    createAndShowSplashScreen();
    }... not my code, but I did contribute "some stuff" ...

  • Follow sprite when the mouse is down, but randomly move when mouse is up?

    I have a sprite that has a Random Movement behavior.
    While the mouse is down, I want it to stop this behavior and initialize a Follow Sprite behavior instead.
    When the mouse is lifted, I want to stop the Follow Sprite behavior and reset/restart the Random Movement behavior.
    Openspark helped me out with a different version of a very similar behavior a long while back, which worked. It switched between Random Movement and Draggable. I tried to edit the code so that it would apply to Follow Sprite instead of Draggable, but it isn't working the way I thought it would.
    The order of behaviors on my sprite is as such:
    followSprite (Follow Sprite)
    moveToward (The behavior described above)
    randomMove (Random Movement)
    turnTowardsMouse (sprite faces mouse when it is clicked)
    Face Destination (if not facing mouse, sprite faces toward the randomized endpoints generated by randomMove)
    This is the moveToward behavior - the middleman that's supposed to be swapping between the two:
    property pSprite
    property pTouching
    on beginSprite(me)
      pSprite = sprite(me.spriteNum)
    end beginSprite
    on mouseDown(me)
      -- Overrule the Random Movement and Rotation behavior until the mouse
      -- is released. See the on prepareFrame() handler for the effect.
      pTouching = TRUE
    end mouseDown
    on prepareFrame(me)
      if pTouching then
        -- Block the event from reaching the Random Movement and Rotation
        -- behavior, so that only the Draggable behavior will work.
        if the mouseDown then
          stopEvent
        else
          -- The user has released the mouse.
          -- Start a new movement in the Random Movement and Rotation behavior.
          pSprite.pPath = VOID
          sendSprite(pSprite, #mNewPath)
          pSprite.pRotate = VOID
          sendSprite(pSprite, #mNewRotation)
          pTouching = 0
        end if
      end if
    end prepareFrame
    Can anyone help me figure this out?
    If you want to imagine a visual, it's essentially a touchscreen fish tank. Fish swim around randomly, but when someone is touching the screen, they approach the point of contact (which is defined by a tiny invisible sprite centered on the cursor).
    Once again, thank you so much to anyone who can help me out. This is part of a capstone undergraduate art project I am doing - and I am far more experienced in making the visuals than I am in coding. I am having to mostly tackle Lingo on my own. Any coding help I've received will be recognized (with permission) on my artist website as well as a thesis paper I am writing that will be published in May.

    As first steps at troubleshooting you could try an SMC reset and a PRAM reset:
    SMC Reset
    Shut down the computer.
    Unplug the computer’s power cord and disconnect peripherals.
    Press and hold the power button for 5 seconds.
    Release the power button.
    Attach the computers power cable.
    Press the power button to turn on the computer.
    Reset PRAM
    Shut down the computer.
    Locate the following keys on the keyboard: Command, Option, P and R.
    You will need to hold these keys down simultaneously in step 4.
    Turn on the computer.
    Press and hold the Command-Option-P-R keys. You must press this key combination before the gray screen appears.
    Hold the keys down until the computer restarts and you hear the startup sound for the second time.
    Release the keys.
    If that doesn't help, what OS are you running? Depending on the OS (Lion/Snow Leopard) will help determine the next step.

  • Character rotation problem in tiled map

    Hi I am trying to rotate the character in a tiled map. Its is successful but theres problem with moving diagonally. When i pressed for example up and right keypressed, when its moving it will rotate as i wanted but when i released the buttons, it either rotate to the up or right. I want the image to rotate diagonally and stay as it is when i released the buttons.
    Here are my source code...I noe its very long but really need someone help...There are 3 java files. (Sorry for dis long and ridiculous codes...)
    1) Game.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    public class Game extends Canvas implements KeyListener
         private BufferStrategy strategy;
         private GameMap map=new GameMap();
         private Player player;
         private boolean left,right,up,down;
         Image ship = Toolkit.getDefaultToolkit().getImage("res/up1.PNG");
         public Game()
              Frame frame = new Frame("Pirate Game");
              frame.setLayout(null);
              setBounds(0,30,480,510);
              frame.add(this);
              frame.setSize(480,510);
              frame.setResizable(false);
              // exit the game
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addKeyListener(this);
              addKeyListener(this);
              frame.setVisible(true);
              createBufferStrategy(2);
              strategy = getBufferStrategy();
              player = new Player(ship, map, 1.5f, 1.5f);
              // start the game loop
              gameLoop();
    public void gameLoop()
              boolean gameRunning = true;
              long last = System.nanoTime();     
              // keep looking while the game is running
              while (gameRunning)
                   Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
                   // clear the screen
                   g.setColor(Color.black);
                   g.fillRect(0,0,480,480);
                   // render our game objects
                   g.translate(0,0); //placing the map to desired location on the frame
                  map.paint(g);
                   player.paint(g);
                   // flip the buffer so we can see the rendering
                   g.dispose();
                   strategy.show();
                   // pause a bit so that we don't choke the system
                   try { Thread.sleep(4); } catch (Exception e) {};
                   long delta = (System.nanoTime() - last) / 1000000;
                   last = System.nanoTime();
                   for (int i=0;i<delta / 5;i++)
                        logic(5);
                   if ((delta % 5) != 0)
                        logic(delta % 5);
         public void logic(long delta) {
              // check the keyboard and record which way the player
              // is trying to move this loop
              float dx = 0;
              float dy = 0;
              if (left)
                   dx -= 1;
              if (right)
                   dx += 1;
              if (up)
                   dy -= 1;
              if (down)
                   dy += 1;
              // if the player needs to move attempt to move the entity
              // based on the keys multiplied by the amount of time thats
              // passed
              if ((dx != 0) | (dy != 0))
                   player.move(dx * delta * 0.0015f,dy * delta * 0.0015f);
         public void keyTyped(KeyEvent e) {}
         public void keyPressed(KeyEvent e)
              if (e.getKeyCode() == KeyEvent.VK_LEFT)
                   left = true;
              if (e.getKeyCode() == KeyEvent.VK_RIGHT)
                   right = true;
              if (e.getKeyCode() == KeyEvent.VK_DOWN)
                   down = true;
              if (e.getKeyCode() == KeyEvent.VK_UP)
                   up = true;
         public void keyReleased(KeyEvent e)
              if (e.getKeyCode() == KeyEvent.VK_LEFT)
                   left = false;
              if (e.getKeyCode() == KeyEvent.VK_RIGHT)
                   right = false;
              if (e.getKeyCode() == KeyEvent.VK_DOWN)
                   down = false;
              if (e.getKeyCode() == KeyEvent.VK_UP)
                   up = false;
         public static void main(String args[])
          new Game();
    2) GameMap.java
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class GameMap
         int width = 15;
        int height =15;
        static final int TILE_SIZE = 32;
             int[][]  A  =  {{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,3,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
                                 {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
        Image sea = Toolkit.getDefaultToolkit().getImage("res/sea.PNG");
        Image rock = Toolkit.getDefaultToolkit().getImage("res/rock.PNG");
         public void paint(Graphics g)
            for(int across = 0; across < width ; across++)
                for(int vert = 0; vert < height ; vert++)
                    if (A[across][vert] == 1)
                    g.drawImage(rock,across*TILE_SIZE,vert*TILE_SIZE,null);
                         else
                         g.drawImage(sea,across*TILE_SIZE,vert*TILE_SIZE,null);
        public boolean blocked(float x, float y)
              return A[(int) x][(int) y] == 1;
    3) Player.java
    import java.awt.Graphics2D;
    import java.awt.Image;
    public class Player {
         private float x;
         private float y;
         private Image image;
         private GameMap map;
         private float ang;
         private float size=0.3f;
         public Player(Image image, GameMap map, float x, float y)
              this.image = image;
              this.map = map;
              this.x = x;
              this.y = y;
         public boolean move(float dx, float dy)
              // new position
              float nx = x + dx;
              float ny = y + dy;
              //check collision
              if (validLocation(nx, ny)) {
                   x = nx;
                   y = ny;
                   // and calculate the angle we're facing based on our last move
                   ang = (float) (Math.atan2(dy, dx) + (Math.PI / 2));
                   return true;
              // if it wasn't a valid move don't do anything apart from tell the caller
              return false;
         public boolean validLocation(float nx, float ny)
              if (map.blocked(nx - size, ny - size))
                   return false;
              if (map.blocked(nx + size, ny - size))
                   return false;
              if (map.blocked(nx - size, ny + size))
                   return false;
              if (map.blocked(nx + size, ny + size))
                   return false;
              return true;
         public void paint(Graphics2D g) {
              int xp = (int) (map.TILE_SIZE * x);
              int yp = (int) (map.TILE_SIZE * y);
              // rotate the sprite based on the current angle and then
              // draw it
              g.rotate(ang, xp, yp);
              g.drawImage(image, (int) (xp - 16), (int) (yp - 16), null);
              g.rotate(-ang, xp, yp);
    }

    rotate() should always be accompanied with appropriate translate().
    See:
    http://java.sun.com/docs/books/tutorial/2d/TOC.html
    http://www.adtmag.com/java/articleold.aspx?id=1241
    http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html
    And, never mix AWT components with Swing ones.
    Use JPanel instead of Canvas.
    Use also standard drawing/painting technique shown above URSs.

  • Need help with 3D carousel gallery rotation to a specific angle

    Hi,
    I am making a 3d gallery, that has a menu underneath it. When clicking to a menu link, the gallery will rotate itself to a certain angle (photo) connected with the menu link. I am using FlashAndMaths 3D cylindrical gallery scripts (XML Customizable 3D Cylindrical Photo Gallery in Flash) as the base (as I couldn't find any free or neither payed 3d galleries that would have a menu connected to the carousel!).
    The function to rotate a carousel of thumbnails is the following:
    public function doRotate(ang:Number):void {  
                if(isLoading || notReady){       
                        return;
                if(!this.contains(container)){
                    return;
                var i:int;
                 for(i=0;i<numCols;i++){
                   colsVec[i].rotationY+=ang;
                   colsVec[i].rotationY=colsVec[i].rotationY%360;
                   if((colsVec[i].rotationY>90+diffAng && colsVec[i].rotationY<270-diffAng) || (colsVec[i].rotationY<-(90+diffAng) && colsVec[i].rotationY>-(270-diffAng))){
                          if(container.contains(colsVec[i])){
                              container.removeChild(colsVec[i]);
                         } else {   
                                   if(!container.contains(colsVec[i])){
                                     container.addChild(colsVec[i]);
    This will rotate the carousel as an infinite loop. However - I need the function to stop at a certain angle e.g. 45% (and/or reset itself to 0%). Another option would be to stop the carousel at a certain thumbnail container.
    The function to create a carousel is here:
    thumbWidth=thumbsArray[0][0].width;
    thumbHeight=thumbsArray[0][0].height;
    colsVec=new Vector.<Column>();
    colHeight=thumbHeight*colLen+(colLen-1)*pxSpace;
    colWidth=thumbWidth;
    rad=galLoader.radius;
    angle=360/numCols;
    container=new Sprite();
    this.addChild(container);
    containerWidth=2*rad;
    vertAddOn=40;
    vertDrop=15;
    containerHeight=colHeight+vertAddOn;
    container.x=containerWidth/2;
    container.y=containerHeight/2+vertDrop;
    contMask=new Shape();
    this.addChild(contMask);
    contMask.x=container.x;
    contMask.y=container.y;
    prepContainer();
    diffAng=Math.round((Math.asin(rad/fL)*180/Math.PI)*1000)/1000; 
    for(i=0;i<numCols;i++){
    colsVec[i]= new Column(thumbsArray[i],pxSpace,rad);
    container.addChild(colsVec[i]);
    colsVec[i].y=0;
    colsVec[i].x=0; 
    colsVec[i].z=0;
    colsVec[i].rotationY=angle*i;
    if((colsVec[i].rotationY>90+diffAng && colsVec[i].rotationY<270-diffAng) || (colsVec[i].rotationY<-(90+diffAng) && colsVec[i].rotationY>-(270-diffAng))){
    if(container.contains(colsVec[i])){
    container.removeChild(colsVec[i]);
    } else {
    if(!container.contains(colsVec[i])){
    container.addChild(colsVec[i]);
    Could anyone help me as I'm out of ideas!

    Hi, well, unfortunately asking help from forums is my last option, there really isn't many people around anymore, who'd use Flash!
    Also, I couldn't find neither free or payed scripts or examples online, that could do this - so, it's just me and forums.
    I really do appreciate that you've tried to help me- I just need a bit clearer reference (as I'm just not really used to use AS), so that I could try to search and/or figure out how to solve that problem.
    By "call doRotate() and pass the difference between the current rotation and the desired rotation.", did you mean something like this:
    private function onEnter(e:Event):void {
    if (rotate){
    this.doRotate(1);
    if(    //so, here I should use something that would locate the desired position, so something like currentFrame or would you have any better ideas?
    // should I also add something like doRotate.stop(); here?
    this.removeEventlistener(Event.ENTER_FRAME,onEnter);
    Or am I going the wrong way?

Maybe you are looking for