AS3 smooth rotation direction - actionscript-3

I'm not very good with radial calculations, I can't imagine thus I can't be sure. I need some explanation of Math.atan2() thing, please.
Usual task - to make an object rotate after the mouse. I get the differences, get the angle, I see angles in the text areas and DIRECTLY the object does follow the mouse. What I need now is everything to be smooth. I need angles to be 0-360 but after 180 object rotation becomes -180 and counts backwards, and mouse rotation becomes -90 after 270 and also counts back to 0.
More deeply, I want a smooth rotation, it means a set speed of say 2 per frame, to meet the mouse angle the shortest way. It takes to set conditions and I can't do that cause I don't even understand the logic of these values. They are almost random! I don't need it to be done or copied, I need to understand to move on so if you could please explain how does it work and what I do wrong...
Code is simple:
angle = Math.atan2(deltaY,deltaX)/(Math.PI/180) + 90; //+90 cause it lacks it to look at the mouse//
Object01.rotation = angle;
So the problem is I don't even get how it works... if 2 values are different the object can't point at the mouse but it does. Numbers lie and if I need something based on these numbers it will be wrong. Very wrong... Need organization. Meaning I want everything to be ready for further coding that will be based on the rotations to not jump up and down cause of misfit ends.
Add: Explanation of how does it happen, what I described above. Why such a chaos of the values? And an advice on how could I arrange it for further coding, just as I said. Animation alone wont work if I want to make rotation an element of important events such as shooting direction and aiming speed. Or changes of speed rotation of a lockpicked lock. Or anything much more complicated that wont work if I don't make straight and clear values: from A to Z, from 1 to 10, no 8s between 2 and 3, no R before B, no mouse angle 270 when object facing it -90 when they both started from 0 and reached 180 together.
Oh, and as I said, mouse facing works but when I try to make a certain speed of chasing mouse the shortest way it turns the object wrong directions in all 4 quarters. I assume it's also about this arctangens thing that has issues with delta values becoming negative in different quarters. And when I change it, some other value goes wrong... So I need to know exactly what I'm doing to know what's wrong and how to fix it. So yep. Need explanation. Please.
Add2: angleZ = Math.atan2(oppSide,adjSide)/(Math.PI/180);
So I divided rotation to 4 quarters, for each I count atan as opp. side to adj. side, then add 90, 180 and 270 respectively. My mouse rotation does 360, but the object that follow through simple object.rotation = angleZ; still goes to 180, then from -180 to 0 on the left side. Why does it ignore the simple command? The rotation fits but I need it to be equal, no surprises! Why is it happening? How can a number I directly set to be equal to another number as a base of the action change itself to the one of same rotation but completely different number? It doesn't even know it's degrees! It's as simple as "object.rotation, please be equal to the number I choose!"

It's just different coordinate systems. Like how x starts at 0 at the left of the stage, goes +x to the right, and -x to the left, object rotation starts at 0˚ pointing up, and goes +180˚ clockwise and -180˚ anti-clockwise.
Math.atan2 happens to start at 0 pointing left (-x), and go +270˚ clockwise and -90˚ anti-clockwise, which is annoying, but it just means you have to convert between coordinate systems by adding 90˚.
You can spin something around over and over of course, so the numbers jump so that they always stay within the same range, because 361˚ is the same as 1˚, and -270˚ is the same as 90˚. You can tell an object to rotate outside of the -180˚ to 180˚ range, and it will normalise the rotation to within those values.
As mitim described, to smoothly animate rotation you'll either need to use Event.ENTER_FRAME, a Timer, or a tweening library like TweenLite. Most tweening libraries can work out the shortest rotation direction for you, but otherwise you can simply calculate both and see which is smaller.

As an idea, since it seems like you know the angle you need to rotate towards and it's direction, would it be easier to just animate towards that angle to get your smooth rotation? Basically treat it like any other animatable property and just add on your rotation speed (2 degrees it looks like) per frame tick, until it reaches the desired rotation.
Find angle amount needed to rotate by
Figure out if clockwise or counter clockwise direction and set the rotation amount. This can be figured out by checking if the angle is great then 180 / positive or negative
Add the rotation amount * direction every frame tick, until the desired rotation is less then or equal to the rotation amount per frame
Set rotation to desired rotation

Related

as3 - how to randomize object positions without colliding?

If I have two instances called block1 and block2. And they move off the stage. It scrolls down the y position and it respawns back on top. But I don't want the x/y position colliding with the other blocks? I want it to respawn back to position, but I want it randomized but at the same time I don't want it touching each other?
Heres my code:
if (block1.y > stage.stageHeight)
{
block1.y = -550;
block1.x = (Math.floor(Math.random() * (maxNum - minNum + 5)) + minNum);
}
I'm pretty sure I'm calculating the respawn coordinates the wrong way, but I'm not sure how to put it in a random x and y position without colliding with other blocks.
A very simple method can be just to spawn your box, do a collision check, then if collision, remove and respawn and recheck until you find an empty spot where it fits
This is obviously quite inefficient, but is pretty simple to implement quickly if you have some sort of collision detection already working. Keep in mind if there is no spot that it can fit in, then it'll loop forever so you may want to set a max try count or something of that sort.
How fast/well it'll actually work will depend on if the spawn area is pretty sparse or pretty dense, which will increase/decrease the percentage that it'll find a good empty spot the first few times.
There is some room for improvement, going down this path though, such as if your collision detection system gives a minimum translation vector, you could just move the new shape over and use that position to spawn.
Other simple methods could involve keeping track of known occupied positions and adjusting your random range to avoid those values.

What is the purpose of setEulerZYX() in bullet physics?

I have been looking into the RagdollDemo and have kind of got stuck in the part where setEulerZYX() is used in basis matrix.
transform.setIdentity();
transform.setOrigin(btVector3(btScalar(-0.35), btScalar(1.45), btScalar(0.)));
transform.getBasis().setEulerZYX(0,0,M_PI_2);
m_bodies[BODYPART_LEFT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_UPPER_ARM]);
I did some research, yet couldn`t fully understand what exactly does this function do and why it is needed. Any help would be very nice.
It is a way (there are others) to set the rotation of the body.
http://bulletphysics.org/Bullet/BulletFull/classbtMatrix3x3.html#a0acce3d3502e34b4f34efd275c140d2a
So this is setting it to 0,0,M_PI_2, M_PI_2 being Pi/2 means this is a rotation on the x axis of 1/4 turn, i.e. 90 degrees.

Gradually rotate towards a direction

I have a car object, and I want it to gradually rotate to the direction where the user clicked.
Every frame I did math to calculate the new direction it needs, and it's stored at car.direction. The actual direction is of course in car.rotation.
Now I want to update the rotation every frame until it's equal to the direction. However I tried everything and can't figure out how to do that.
By the way, I'm using FireFly, that is a gameengine built on top of Starling Framework, But I don't think it's relevant.
I would go with Marty's suggestion, use the smallestAngle function to determine which direction you should be rotating. Basically you can move some percentage of the smallestAngle during every frame update until the percentage of that smallestAngle is below some threshold (and have it "snap" the rest of the way).
Something like
//each time this is called it will get 1/4 closer, but never get to 0, hence the need for a threshold avoid paradoxes
//http://en.wikipedia.org/wiki/Zeno's_paradoxes#Dichotomy_paradox
var angleToMove:Number = smallestAngle()/4; //the divide by 4 here means get 1/4 of the angle gap closer each time this function is called, I assume this is on a timer or frame handler, making the 4 greater will make it follow more slowly, making it lower will make it follow more quickly, never reduce to or below 0 unless you want wonkiness
if(angleToMove<someRadianThreshold)
angleToMove = smallestAngle();
//use angleToMove to adjust the current heading/rotation

What's the purpose of Canvas.Context Save and Restore in this example?

This page shows some animations in HTML5 canvas. If you look at the source of the scroller, there's a statement to save the context after clearing the rectangle and restoring it after the animation. If I substitute the restore statement with another ctx.clearRect(0, 0, can.width, can.height statement, nothing works. I thought the restore is restoring the cleared rectangle but it seems its restoring more info. What's that extra info that's needed for the next frame?
I am not looking for HTML5 textbook definitions of Save and Restore but I want to understand why they are needed in this specific example.
UPDATE
It's frustrating to get an answer where I specifically already mentioned in the question I don't want to get the definitions of save() and restore(). I already know Save() saves the state of the context and Restor()e restores it. My question is very specific. Why is restore() used in the manner in the example when all the Save did is saved an empty canvas. Why is restoring an empty canvas not the same as clearing it?
Canvas state isn't what's drawn on it. It's a stack of properties which define the current state of the tools which are used to draw the next thing.
Canvas is an immediate-mode bitmap.
Like MS Paint. Once it's there, it's there, so there's no point "saving" the current image data, because that would be like saving the whole JPEG, every time you make a change, every frame...
...no, the state you save is the state which will dictate what coordinate-orientation, dimension-scale, colour, etc, you use to draw the NEXT thing (and all things thereafter, until you change those values by hand).
var canvas = document.createElement("canvas"),
easel = canvas.getContext("2d");
easel.fillStyle = "rgb(80, 80, 120)";
easel.strokeStyle = "rgb(120, 120, 200)";
easel.fillRect(x, y, width, height);
easel.strokeRect(x, y, width, height);
easel.save(); // stores ALL current status properties in the stack
easel.rotate(degrees * Math.PI / 180); // radians
easel.scale(scale_X, scale_Y); // any new coordinates/dimensions will now be multiplied by these
easel.translate(new_X, new_Y); // new origin coordinates, based on rotated orientation, multiplied by the scale-factor
easel.fillStyle = "gold";
easel.fillRect(x, y, width, height); // completely new rectangle
// origin is different, and the rotation is different, because you're in a new coordinate space
easel.clearRect(0, 0, width, height); // not even guaranteed to clear the actual canvas, anymore
easel.strokeRect(width/2, height/2, width, height); // still in the new coordinate space, still with the new colour
easel.restore(); // reassign all of the previous status properties
easel.clearRect(0, 0, width, height);
Assuming that you were only one state-change deep on the stack, that last line, now that your canvas' previous state was restored, should have successfully cleared itself (subpixel shenanigans notwithstanding).
So as you can see, it has very, VERY little to do with erasing the canvas.
In fact, it has nothing to do with erasing it, at all.
It has to do with wanting to draw something, and doing the basic outlining and sweeping colours/styles, and then manually writing in the colours for the smaller details on top, and then manually writing all of the styles back the way they were before, to go back to sweeping strokes for the next object, and on and on...
Instead, save general states that will be reused, create a new state for smaller details, and return to the general state, without having to hard-code it, every time, or write setter functions to set frequently-used values on the canvas over and over (resetting scale/rotation/affine-transforms/colours/fonts/line-widths/baseline-alignment/etc).
In your exact example, then, if you're paying attention, you'll see that the only thing that's changing is the value of step.
They've set the state of a bunch of values for the canvas (colour/font/etc).
And then they save. Well, what did they save?
You're not looking deep enough. They actually saved the default translation (ie: origin=0,0 in original world-space).
But you didn't see them define it?
That's because it's defined as default.
They then increase the step 1 pixel (actually, they do this first, but it doesn't matter after the first loop -- stay with me here).
Then they set a new origin point for 0,0 (ie: from now on, when they type 0,0 that new origin will point to a completely different place on the canvas).
That origin point is equal to x being the exact middle of the canvas, and y being equal to the current step (ie: pixel 1 or pixel 2, etc... and why the difference between starting at 0 and starting at 1 really doesn't matter).
Then what do they do?
They restore.
Well, what have they restored?
...well, what have they changed?
They're restoring the point of origin to 0,0
Why?
Well, what would happen if they didn't?
If the canvas is 500px x 200px, and it starts at 0,0 in our current screen space... ...that's great...
Then they translate it to width/2, 1
Okay, so now when they ask to draw text at 0,0 they'll actually be drawing at 250, 1
Wonderful. But what happens next time?
Now they're translating by width/2, 2
You think, well, that's fine... ...the draw call for 0,0 is going to happen at 250, 2, because they've set it to clear numbers: canvas.width/2, 2
Nope. Because current 0,0 is actually 250,1 according to our screen. And one translation is relative to its previous translation...
...so now you're telling the canvas to start at it's current-coordinates' 0,0 and go left 250, and down 2.
According to the screen (which is like a window, looking at the map, and not the map, itself) we're now 500px to the right, and 3 pixels down from where we started... And only one frame has gone by.
So they restore the map's coordinates to be the same origin as the screen's coordinates (and the rotation to be the same, and the scale, and the skew, etc...), before setting the new one.
And as you might guess, by looking at it, now, you can see that the text should actually move top to bottom. Not right to left, like the page says...
Why do this?
Why go to the trouble of changing the coordinate-system of the drawing-context, when the draw commands give you an x and y right there in the function?
If you want to draw a picture on the canvas, and you know how high and wide it is, and where you'd like the top-left corner to be, why can't you just do this:
easel.drawImage(myImg, x, y, myImg.width, myImg.height);
Well, you can.
You can totally do that. There's nothing stopping you.
In fact, if you wanted to make it zoom around the screen, you could just update the x and y on a timer, and call it a day.
But what about if you were drawing a game character? What if the character had a hat, and had gloved hands, and big boots, and all of those things were drawn separate from the character?
So first you'd say "well, he's standing at x and y in the world, so x plus where his hand is in relation to his body would be x + body.x - hand.x...or was that plus..."
...and now you have draw calls for all of his parts that are all looking like a notebook full of Grade 5 math homework.
Instead, you can say: "He's here. Set my coordinates so that 0,0 is right in the middle of my guy". Now your draw calls are as simple as "My right hand is 6 pixels to the right of the body, my left hand is 3 pixels to the left".
And when you're done drawing your character, you can set your origin back to 0,0 and then the next character can be drawn. Or, if you want to attempt it, you can then translate from there to the origin of the next character, based on the delta from one to the other (this will save you a function call per translation). And then, if you only saved state once the whole time (the original state), at the end, you can return to 0,0 by calling .restore.
The context save() saves stuff like transformation color among other stuff. Then you can change the context and restore it to have the same as when you saved it. It works like a stack so you can push multiple canvas states onto the stack and recover them.
http://html5.litten.com/understanding-save-and-restore-for-the-canvas-context/

Help with velocity vectors

I have a velocity vector that is V(233, 188).
It makes an object moves toward the right-bottom side of the screen in 300 pixels per second when the origin is V(0, 0).
When the position of the object is, for instance, (592, 334), I set the velocity vector to V(294, 55) but the object does not start moving toward that direction... It keeps moving the same direction, but it seems that it makes a small curve of 10 degrees...
What I'm doing is:
objectLocation += velocity * elapsedTime;
What am I doing wrong?
The difference between (233,188) and (294,55) is not that much, in the grand scheme of things. To verify your code is working, try a vector such as (200,-200). That will cause it to actually bounce off the point in the y-direction.
If that code works, then it's just your values that aren't working.