Center pivot point on a sprite

There’s been a long time since I’ve updated this place. Well, real life has gotten me. My time has been divided between work, and Diablo 3 (yeah I know….). These days at work have been very anxious (and still are). There are a tons of things that I want to write, tons of game tutorials I want to add up, but I just keep delaying it. My bad I suppose, but it’s never too late (or so they say).

This time I had an old school problem in as3. I wanted to rotate a sprite, with its pivot point centered. But as you probably know in as3 the pivot point is always at the top left of the sprite, and it can’t be moved except if you are using Adobe CS Flash. Actionscript junkies are left ouf of this. Now there is an algorithm based on mathematics that you can use, but there is an even easier way for this. You probably know it but as I am self-taught I didn’t and spent a lot of time to find it, I guess I could help others who doesn’t know it either.

So to cut to the chase, as you add a DisplayObject to a sprite, you can set its x and y values to minus the half of them.

object.x = -object.width / 2;
object.y = -object.height / 2;

As simple as that :). Live example here.

Advertisements

Posted on 7 October, 2012, in Actionscript 3, Programming and tagged , , , , . Bookmark the permalink. 2 Comments.

  1. Alternatively you can create an object as a container and add as a child the object you want to rotate. Name the container object “pivot”. Now you can offset the child object inside the first container and use the parent as the pivot point.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: