Reputation: 163
I want this object to rotate around its center rather than the top left corner. The code looks like this:
switch (event.keyCode)
{
case 37:
car.rotation = -90;
car.x -= 5;
break;
So when i press the left key, the car turns left but as it is now it jumps up a bit because its rotating around the top corner.
Thanks
Upvotes: 10
Views: 23222
Reputation: 433
Re-posting solution by Mallario from OpenFL community: https://community.openfl.org/t/rotation-around-center/8751/9 that does not use the transform.matrix
. I adapted it in Haxe, but it is almost the same in ActionScript 3.
package p.util;
import openfl.display.DisplayObject;
using p.util.FloatUtilities;
class DisplayObjectUtilities {
/**
* Positions and rotates a display object by its center anchor.
*/
public static function centerOrient(object: DisplayObject, x: Float, y: Float, rotation: Float) {
var w = object.width;
var h = object.height;
x -= w / 2;
y -= h / 2;
object.rotation = rotation;
// Code from https://community.openfl.org/t/rotation-around-center/8751/9
{
var hypotenuse = Math.sqrt(w / 2 * w / 2 + h / 2 * h / 2);
var newX = hypotenuse * Math.cos((rotation + 45.0).toRadians());
var newY = hypotenuse * Math.sin((rotation + 45.0).toRadians());
x -= newX;
y -= newY;
}
object.x = x;
object.y = y;
}
}
Upvotes: 0
Reputation: 13522
The following will rotate around center :
public function rotateAroundCenter(object:DisplayObject, angleDegrees:Number):void {
if (object.rotation == angleDegrees) {
return;
}
var matrix:Matrix = object.transform.matrix;
var rect:Rectangle = object.getBounds(object.parent);
var centerX = rect.left + (rect.width / 2);
var centerY = rect.top + (rect.height / 2);
matrix.translate(-centerX, -centerY);
matrix.rotate((angleDegrees / 180) * Math.PI);
matrix.translate(centerX, centerY);
object.transform.matrix = matrix;
object.rotation = Math.round(object.rotation);
}
It translates the center of the object to 0,0 then rotate it and then translate it back.
Upvotes: 22
Reputation: 547
The easiest way to accomplish this is to add your car sprite/movieclip onto another sprite, where the x and the y coordinates are half the width and height properties. If the car is drawn in adobe flash you can also drag it to the top left, so that the center point is in the middle.
Upvotes: 8