October 16th, 2008

Sprite: Properly update properties

Simple: update the x property of a bunch of Sprites on the stage based on the Mouse’s x position.

If you are on the right half of the stage, move objects to the left (scroll right/negative x). If you are on the left side of the stage, move objects to the right (left scroll/positive x). This also takes into account how close you are to the center; if you are closer to the edges, scroll faster.

This is accomplished using an ENTER_FRAME handler and other fancy Math is happening but essentially we have:

layer.x -= _curRatio * _speed[layer];

All this is doing is updating the x property of a particular ‘layer’ object. And the result of this is not satisfactory by any means. Why do the objects seem to not be updating properly? And what is the solution?

The theory here is that Flash cannot redraw the object while attempting to update the property which is changing it (x, y, alpha, rotation). To accommodate this quirk is a simple fix; simply set a variable on the Sprite, update that property and then update the x property based on said variable.

layer.xPos -= _curRatio * _speed[layer];
layer.x = layer.xPos;

Simple and effective.

I’m betting that many people incorrectly use this technique but really can’t tell and this never notice. However when one has things scrolling at a particular rate (layers) where one can visibly see the discrepancy it all becomes apparent rather quickly.

Thanks to Daniel.