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
Similar Messages
-
3D Rotating on it's own center axis problem...
Need some help here. This is my first time using 3D in flash.
I have a movieclip (picture 80 x 80 pix) that I am tweening to look like it is rotating like face of a cube.
What I did:
1. I transformed the z-axis to "raise" the picture off of the y axis.
2. Then I rotated it around the y-axis from one end of my tween to the other.
Looks great when I scroll through the movie clip's time line but (starts on right almost paper thing, rotates to center square, and continues to the left again paper thin) The problem is when I place it on the stage and preview the swf, it rotates around its own center point and not the offset y-axis.
If I convert it to frame by frame animation, it works but I don't want to do that.
Please advise someone.
Thanks!Sorry if I don't' quite get it, but my other thread was about the movieclip defaulting to the stages coordinates. In this case my movieclip's animation is rotating around the symbols center point and not around the y-axis as I would like.
I can move the transform the symbol from axis point to another and it is fine but in this case i am only rotating it but after I placed is away from the y-axies. I expect it to "orbit" around the y axis continually facing it...and it does when I move through the tweaned frames, but when I publish the swf, it no longer "orbits" around the y-axis but rather just spins around it's center point.
I hope this is a little clearer, and thanks for your other answer. I'll plug that code in as soon as I can. -
Model rotation about multiple axis
Can anyone tell me how I can limit the rotation of a model to
a specific angle without using camera rotation?
I do know how to limit the rotation when the model has only
been rotated in one axis (simple maths comparison of either x, y,
or z depending on which axis I've rotated the model about).
But, how do you limit rotation when the model has already
been rotated about 1 or 2 of the other axes given that x, y, and z
keep changing their values and axisAngle doesn't always give
appropriate values?Using parent/childs is one way to work around relative
rotation problems. Parent the model you are trying to limit
rotation on to a dummy model (or group). Keep the dummy at
rotation(0, 0, 0), and rotate the target model to its correct
orientation in your scene. Then monitor the dummy's rotation to
keep it within your limits. -
Here's my test:
http://media.putfile.com/shaketrack
As you can see, X and Y tracking work fine.
However, how can I do rotation and Z axis tracking?You need a two point track and you need to tell Shake to interpret the information as rotation, size, or both...
Patrick -
How to use Behavior to rotate to z axis?
You are so brief, this is the best I can tell you:
Use a Transform3D that you put into a TransformGroup node placed over the brach that has to be rotated, and make your behaviour create a new Transform3D o change the already existing one and then set whichever of both you choose, again in the TransformGroup. This basically descrives the general method to change a trasnformation, just make your behaviour do it on your own criteria (on key presses, mouse movement, time, etc.)
Anyway there are some predefined behaviours you could benefit from, check the tutorials.
Regards -
Another Question...rotating on two axis
Hi again. Well I have yet another question...how do I set a translation to rotate on two axis? Like I know that I can do:
TransformGroup tg;
Transform3D t3d = new Transform3D();
t3d.setRotation(new AxisAngle4f(1f,0f,0f,(some angle)));
tg.setTransform(t3d);
for one axis (I just put the declarations in to show an example) but if I try to apply two set rotations or two Transform3D's it doesn't work...so how would I rotate on, say, both the x and the y axis? Thanks,
Compaqin fact the best thing would be to get used to quaternions. I suppose some Java3D tutorials discribe it quite well.
If you really want to use rotation on axis you have two solutions :
create 2 Transform3D and apply the result
Transform3D t3dx = new Transform3D();
t3dx.setRotation(new AxisAngle4f(1f,0f,0f,(xangle)));
Transform3D t3dy = new Transform3D();
t3dy.setRotation(new AxisAngle4f(0f,1f,0f,(yangle)));
t3dx.mul(t3dy);
tg.setTransform(t3dx);
(hum, at least i suppose it would work ;)
or you can do that too :
Transform3D t3dx = new Transform3D();
t3d.setRotation(new AxisAngle4f(1f,yangle/xangle,0f,(xangle)));
tg.setTransform(t3d);
(in this case xangle must be != 0)
I'm not really sure it will work so please tell me if it works. I've tried to help you twice today so you can send me some bucks to the folowing address :
oh, ok mum i won't give our address on the internet ;)
c ya
GnG -
Animate a cube to rotate around x axis!!!
Hi! I'm trying to animate a cube to rotate around x axis using RotationInterpolator object.
Can anyone kindly tell me how I can do that? I've seen the example at Sun's 3d tutorial but they use the default behavior which is rotating around y axis.
Thanks in advance.
--DMlol
in fact the axis used in the RotationInterpolator is the one which is on the y axis in the local coordinates system obtained after the Transform3D is performed
for example:
- if you use only new Transform3D(), which does nothing, the axis will be y
- but if you use rotz(), this transform3D transforms the old x axis into the new y one, the old y axis into the new -x one and the old z axis into the new z one. Thus in the new local coordinates system obtained, the new y axis matches the old x axis, so this x axis is used for the interpolator
I don't know if I'm very clear, it's difficult to explain and I'm French ;)
see the java 3D API :
http://java.sun.com/products/java-media/3D/forDevelopers/J3D_1_3_API/j3dapi/javax/media/j3d/RotationInterpolator.html#RotationInterpolator(javax.media.j3d.Alpha, javax.media.j3d.TransformGroup, javax.media.j3d.Transform3D, float, float) -
Hi all !!!
I am a novice to 3d programming but i have done some JAVA programming earlier.
The problem i am finding is that I do not know how to rotate any geometric object (say, a cylinder or a cone) about any arbitrary axis, say ax+by+c=0.
Can anybodyhelp me ???
Thanks in advance.
AjayI am pretty sure I know what you are talking about.
//Create the Object
//Create a transform group for your object
TransformGroup tg = new TransformGroup();
// Now you need to make a Transform3D to do the rotational work
Transform3D tr = new Transform3D();
//To rotate around any axis use setRotation and pass
// is a Quat4D (or f,i)
// Quat takes 4 arguments x,y,z,w use the x,y and z to
// create a vector to rotate around. i.e. (0,1,0,.4) would
// rotate arount the Y axis, (1,1,0, .4) would rotate
// around a line between x,y.
// The W in the Quat is the angle to rotate (in Radian 0-2Pi);
//So ...
tr.setRotation( new Quat4d(1,1,0,.4));
tg.setTransform(tr);
//Add your object to your transform group
tg.addChild(your_object);
//Add your TRansformGroup to the world
root.addChild(tg); //or whatever your BranchGroup is called
I hope that is what you wanted. And does what you need. -
Rotate a Object Around Center Axis
Hey peoples, new to flash here. I'm using CS3 with ActionScript 3.0. What I want is simple, and I've done some searching but nothing that can get me the right results. I'm going to post a link that does exactly what I want:
http://www.newgrounds.com/dump/item/d25a3dd46f2ff49f2ec892c425cbbd1e
This rotates the circular object around a center point in a way that you can distort the object yet is still remains turning in a circular motion. A simple motion tween rotating the image will only work if the object is perfectly round, so distorting the object to make it more straight or curved won't work with a simple tween. I want to do exactly what is happening here (with my own object), is there some AS3 behind the scenes here making this turn on a center point?? Thanks for the helpYes, but I still don't know what you mean by the parent child relationship. Lets say I use a simple rotate line like:
objectname.rotation = 360;
That should spin it, but how do I spin it correctly if the object is skewed like in the bottom right picture of my example? -
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. -
IPad 1 has a rotating icon center of screen, iPad 1 has a rotating icon center of screen
iPad 1 has a rotating circle in the center of the screen won't turn off
Try a reset:
Hold the Sleep and Home button down for about 10 second until you see the Apple logo. -
How to limit rotation around an axis
Hello!
I am using Mouse Rotate to rotate an object around it's axis:
MouseRotate mouseRotate = new MouseRotate();
mouseRotate.setTransformGroup( sectionTransform );
mouseRotate.setSchedulingBounds( new BoundingSphere() );
mouseRotate.setFactor( 0, 0.3 );
Currently it rotates 360 degrees, but I would like to be able to limit the rotation angle to say 180. Could you please help me out?
Thanks!
Anna.You might want to consider creating your own behaviour. It depends on your implementation, but if you have a Transform group above the object, you can get the transform and get the rotation values from that transform. It will take a bit of math, but here's a primer to get you started...
http://www.martinb.com/maths/geometry/rotations/conversions/index.htm
http://www.martinb.com/maths/geometry/rotations/conversions/matrixToEuler/index.htm
so if you calculate the angle around a particular axis from that transform and it is "greater" than the limit, then you can just set the transform's rotation angle to the limit by reconstructing a new transform and placing that transform in the transform group.
Anyway, I dont know if that helps. It really depends on what you have as far as implementation thus far. My best suggestion is to try to create your own rotation behaviour.
Cheers,
Greg -
AffineTransform rotate+resize+center
I have an image in landscape format. This image should be rotated 90 degrees (into portrait format) then resized to fit screen (by height) and finally centered on the screen. I'll like to use AffineTransform to do this task, but I cannot figure out have to make the translation so the picture is centered on the screen.
What is needed to make the following code work?
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.geom.*;
public class RotateAndResize extends JFrame
public static Image image;
public static void main(String[] args) throws Exception
//A photo (in landscape format) which need to be rotated 90 degress (to portrait format)
File thumbFile = new File("C:\\...\\P1080309.jpg");
image = javax.imageio.ImageIO.read(thumbFile);
RotateAndResize frame = new RotateAndResize();
frame.setSize(800,600);
frame.setVisible(true);
public void update ( Graphics g )
paint(g);
public void paint(Graphics in)
Graphics2D g = (Graphics2D) in;
int w = getWidth();
int h = getHeight();
int imgWidth = image.getWidth(null);
int imgHeight = image.getHeight(null);
g.setColor (new Color(0,0,0));
g.fillRect (0,0,w,h);
//switch due to rotation
int tmp = imgHeight;
imgHeight = imgWidth;
imgWidth = tmp;
double scale = Math.min((double)w/imgWidth, (double)h/imgHeight);
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
at.quadrantRotate(1); //90
g.setTransform ( at );
g.drawImage(image
,w/2 - imgWidth / 2 //center
,h/2 - imgHeight / 2 //center
,imgWidth
,imgHeight
,null);
}First and foremost:
1. Always create and show Swing components on the EDT using SwingUtilities (or EventQueue) #invokeLater.
2. Never draw to a JFrame, it's a top level container and is meant to hold other components. Do custom painting in a JCompoent or JPanel subclass. See [the Tutorial|http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html].
3. Your GUI is not a special type of JFrame and should not subclass JFrame. Always prefer composition over inheritance.
Is this an exercise to use AffineTransform? I usually find it easier to work with the Graphics2D API.import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LandscapeToPortrait {
Image image;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LandscapeToPortrait().makeUI();
public void makeUI() {
try {
// change the filename to your image file
image = ImageIO.read(new File(
"E:/TestImage.jpg"));
// scale to screen size, landscape mode
image = image.getScaledInstance(800, 600, Image.SCALE_SMOOTH);
} catch (IOException ex) {
ex.printStackTrace();
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
int panelWidth = getWidth();
int panelHeight = getHeight();
double scale = (double) panelHeight / imageWidth;
Graphics2D g2 = (Graphics2D) g.create();
// translate to the center of the panel
g2.translate(panelWidth / 2, panelHeight / 2);
// rotate 90°
g2.rotate(Math.PI / 2);
// translate to the point where the top-right of the
// image should paint. Remember that when rotated 90°,
// +x -> +y and +y -> -x
// [0,5] [0,0]
// +----------------+
// | |
// | |
// | |
// | |
// | |
// | |
// | |
// +----------------+
// [5,5] [5,0]
// Also remember that the image will be scaled when painted
g2.translate(-panelHeight / 2, -imageHeight * scale / 2);
// apply the scale
g2.scale(scale, scale);
g2.drawImage(image, 0, 0, this);
g2.dispose();
panel.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}db -
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/ -
Transform combination for rotation about arbitrary axis
I have read through many of the postings about rotations around axes other than ones going through the origin, and they list various solutions. I tried using the method where an object is translated to the origin, rotated, and then translated back to its original position.
When using this method, does each translation and rotation need to be in a separate TransformGroup, or can one TransformGroup use three Transform3D objects multiplied together to reach the same result?
Thanks for any additional info anyone can provide.You can use only one TransformGroup with the combined transformation. However if you change something you have to recalculate the overal transformation again. Thus you have to store the translation and rotation values. If you use seperate TransformGroups Java3D is calculating the overal transformation for you. In this case: if the capability bits which allow changes to the Trasnformation are NOT set and the scene graph is compiled, then j3d will internally hold only the combined transformation, so you don't loose any performance.
Maybe you are looking for
-
RT: How do I use two independen​t Ethernet ports?
I have looked around at the forums and seems like no one has had a real solid answer or example on how to use 2 Ethernet ports with RT. Right now I have two connections configured on the RT: Primary Connection: IP:192.168.2.181 Subnet mask: 255.255.2
-
I have some audiobooks on Cd. they are proper genuine copies. I just can't get them into the audio books section of the itunes library. can anyone help please? Marie
-
Hi Everyone, I have a problem with the my I phone 5 (32gb) , am not able to activate my face time Nor my I message , I have tried all the listed recommendation listed in the site but it didn't work ? any one could help? Thank you
-
Best practices for IPMP and LDoms?
Having read the Oracle VM Server for SPARC 2.0 Administration Guide, it seems to imply that it might be possible to configure IPMP in the control domain (i.e. between the virtual switch interfaces), eliminating the necessity to configure IPMP on each
-
hi, Can any one please provide the link or documnet which states the step by step to configure emctl. I tried but i am getting lot of errors: 1.Agent is not running or when i did emca -config all db -repos create i got the following errors from log r