Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

actionscript 3 - Optimizing transition/movement smoothness for a 2D flash game

Update 6:

Fenomenas suggested me to re-create everything as simple as possible. I had my doubts that this would make any difference as the algorithm remains the same, and performance did not seem to be the issue. Anyway, it was the only suggestion I got so here it is:

  1. 30 FPS: http://www.feedpostal.com/test/simple/30/SimpleMovement.html
  2. 40 FPS: http://www.feedpostal.com/test/simple/40/SimpleMovement.html
  3. 60 FPS: http://www.feedpostal.com/test/simple/60/SimpleMovement.html
  4. 100 FPS: http://www.feedpostal.com/test/simple/100/SimpleMovement.html

The code:

package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.utils.getTimer;

    [SWF(width="800", height="600", frameRate="40", backgroundColor="#000000")]

    public class SimpleMovement extends Sprite
    {
        private static const TURNING_SPEED:uint = 180;
        private static const MOVEMENT_SPEED:uint = 400;
        private static const RADIAN_DIVIDE:Number = Math.PI/180;
        private var playerObject:Sprite;
        private var shipContainer:Sprite;
        private var moving:Boolean = false;
        private var turningMode:uint = 0;
        private var movementTimestamp:Number = getTimer();
        private var turningTimestamp:Number = movementTimestamp;

        public function SimpleMovement()
        {
            //step 1: create player object
            playerObject = new Sprite();
            playerObject.graphics.lineStyle(1, 0x000000);
            playerObject.graphics.beginFill(0x6D7B8D);
            playerObject.graphics.drawRect(0, 0, 25, 50);
            //make it rotate around the center
            playerObject.x = 0 - playerObject.width / 2;
            playerObject.y = 0 - playerObject.height / 2;
            shipContainer = new Sprite();
            shipContainer.addChild(playerObject);
            shipContainer.x = 100;
            shipContainer.y = 100;
            shipContainer.rotation = 180;
            addChild(shipContainer);

            //step 2: install keyboard hook when stage is ready
            addEventListener(Event.ADDED_TO_STAGE, stageReady, false, 0, true);

            //step 3: install rendering update poll
            addEventListener(Event.ENTER_FRAME, updatePoller, false, 0, true);
        }

        private function updatePoller(event:Event):void
        {
            var newTime:Number = getTimer();

            //turning
            if (turningMode != 0)
            {

                var turningDeltaTime:Number = newTime - turningTimestamp;
                turningTimestamp = newTime;
                var rotation:Number = TURNING_SPEED * turningDeltaTime / 1000;
                if (turningMode == 1) shipContainer.rotation -= rotation;
                else shipContainer.rotation += rotation;
            }

            //movement
            if (moving)
            {
                var movementDeltaTime:Number = newTime - movementTimestamp;
                movementTimestamp = newTime;
                var distance:Number = MOVEMENT_SPEED * movementDeltaTime / 1000;
                var rAngle:Number = shipContainer.rotation * RADIAN_DIVIDE; //convert degrees to radian
                shipContainer.x += distance * Math.sin(rAngle);
                shipContainer.y -= distance * Math.cos(rAngle);
            }
        }

        private function stageReady(event:Event):void
        {
            //install keyboard hook
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown, false, 0, true);
            stage.addEventListener(KeyboardEvent.KEY_UP, keyUp, false, 0, true);
        }

        private final function keyDown(event:KeyboardEvent):void
        {
            if ((event.keyCode == 87) && (!moving))  //87 = W
            {
                movementTimestamp = getTimer();
                moving = true;
            }
            if ((event.keyCode == 65) && (turningMode != 1)) //65 = A
            {
                turningTimestamp = getTimer();
                turningMode = 1;
            }
            else if ((event.keyCode == 68) && (turningMode != 2)) //68 = D
            {
                turningTimestamp = getTimer();
                turningMode = 2;
            }
        }

        private final function keyUp(event:KeyboardEvent):void
        {
            if ((event.keyCode == 87) && (moving)) moving = false; //87 = W
            if (((event.keyCode == 65) || (event.keyCode == 68)) && (turningMode != 0)) turningMode = 0; //65 = A, 68 = D
        }
    }
}

The results were as I expected. Absolutely no improvement. I really hope that someone has another suggestion as this thing needs fixing. Also, I doubt it's my system as I have a pretty good one (8GB RAM, Q9550 QuadCore intel, ATI Radeon 4870 512MB). Also, everyone else I asked so far had the same issue with my client.

Update 5: another example of a smooth flash game just to demonstrate that my movement definitely is different! See http://www.spel.nl/game/bumpercraft.html

Update 4: I traced the time before rendering (EVENT.RENDER) and right after rendering (EVENT.ENTER_FRAME), the results:

rendering took: 14 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 14 ms
rendering took: 14 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 24 ms
rendering took: 18 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 232 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 16 ms
rendering took: 12 ms
rendering took: 14 ms
rendering took: 12 ms

The range is 12-16 ms. During these differences, the shocking/warping/flickering movement was already going on. There is also 1 peak of 232ms, at this time there was a relatively big warp. This is however not the biggest problme, the biggest problem are the continuous small warps during normal movement. Does this give anyone a clue?

Update 3: After testing, I know that the following factors are not causing my problem:

  • Bitmap's quality -> changed with photoshop to an uglier 8 colours optimized graphic, no improvement at all.
  • Constant rotation of image while turning -> disabled it, no improvement at all
  • Browser rendering -> tried to use the flash player standalone, no improvement at all

I am 100% convinced that the problem lies in either my code or in my algorithm. Please, help me out. It has been almost two weeks (1 week that I asked this question on SO) now and I still have to get my golden answer.

Update 1: see bottom for full flex project source and a live demo demonstrating my problem.

I'm working on a 2d flash game. Player ships are created as an object:

ships[id] = new GameShip();

When movement and rotation information is available, this is being directed to the corresponding ship:

ships[id].setMovementMode(1); //move forward

Now, within this GameShip object movement works using the "Event.ENTER_FRAME" event:

addEventListener(Event.ENTER_FRAME, movementHandler);

The following function is then being run:

<code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know if there's any golden answer here, but I do have a couple of suggestions.

First, I'd dispense with any inquiries into things like optimizing Math.PI/180, and so on. The generally high framerate should make it clear that simple calculations are not slowing anything down.

Second, to address the occasional spikes of display lag: These look to me very much like the garbage collector is running very frequently. On a very brief look through your code I didn't see any obvious causes of frequent GCs, but I do have two suggestions. First, if you have access to the Flash IDE, I'd try recreating your project without using the Flex framework. A Flash project doesn't include any code except what you put in, but Flex employs a lot of its own arcanery, which may not always be obvious, and some interaction between your code and the framework might be causing GCs.

If that doesn't help, the other thing to try would be to make a greatly simplified version of your code (in Flash if possible), which would hopefully be simple enough not to trigger the same spikes. I mean, for example, a single class attached to the graphic, which merely has one listener for key events and a second listener for frame (or timer) events, within which no variables are created. If a minimal version doesn't display these spikes, then it ought to be possible to triangulate between that and your full client, to figure out what's causing the spikes.

Finally, regarding the general smoothness, my only comment would be that Flash's screen updates are inherently slightly uneven, and realistically you only have two approaches available. Either you move your actors according to frame updates, which makes their movement slightly uneven as framerates vary, or you move them according to elapsed time, which makes their overall movement smooth (in pixels per second) but their display slightly uneven (in pixels moved per frame). The difference is magnified at higher FPS.

Also, it's important to remember that after Flash has made its updates, how they appear on your screen is heavily influenced by your video card. Especially you'll find that shearing and vsync issues can be highly noticeable in one environment and absent in another. There's no real way the developer can address this, except to generally avoid very high-FPS animations and keep the overall processor burden as low as possible.

edit: For more on what I mean about frame update timing being "inherently uneven", please see this blog post. The delay between screen updates varying between 12-16ms is not something you can do anything about; it's a result of the fact that the OS and the browser influence the way Flash's timing works. (It's also something you'll see even in an empty movie, which is why the many comments in this thread about optimizing math and so on are not going to help you.) You can't avoid this kind of variation, but as I said above, you can tailor you visual effects to evoke the effect you want. Either way, I think the spikes are much more worth worrying about. The variation you're looking at is subtle, and will be hard to notice in a game with lots of stuff going on, but the spikes are egregious.

edit 2 You ask: "Do you really think that those smooth games use the same movement algorithm as I do?"

The answer is, I think they're doing something much simpler. They're almost certainly doing one of the following:

function onEnterFrame() { // move at a constant speed per frame
    ship.angle += dtheta;
    ship.x += speed * Math.cos( ship.angle );
    ship.y += speed * Math.sin( ship.angle );
}

function onEnterFrame2() { // move at a constant speed per second
    var dt:Number = getTimeSinceLastFrame();
    ship.angle += anglePerSecond * dt/1000;
    var dist:Number = speedPerSecond * dt/1000;
    ship.x += dist * Math.cos( ship.angle );
    ship.y += dist * Math.sin( ship.angle );
}

In other words, either move a constant distance per frame, or a constant distance per second. Those are the two simplest ways you can approach this, and are the two options that are going to result in the smoothest appearance in Flash. They'll look identical at a constant framerate, and the latter method will look smoother at slightly varying framerates for reasons similar to the "temporal aliasing" mentioned in the article you linked. But the choice between these methods really comes down to, if a CPU spike occurs, after it's over do you want the ship to have kept moving or not? Which is really a game design question. One thing I've done in the past is to use the second method, while clamping dt to at most 2 or 3 times the duration of an ideal frame (1/fps).

As you've probably noticed, the two methods I just recommended are exactly what the "Fix your timestep!" article says not to do. This is because that article is about numerically integrated physics engines, and that's not what you're doing. If you start implementing springs and gravity, then yes, whenever the timesteps get large it will introduce a lot of error, because for that kind of simulation, to oversimplify things, the error depends on the size of the timestep. In what you're doing, it doesn't, so occasional large timesteps don't affect the correctness of the simulation.

Reply to update 6

First, I didn't tell you your problem was performance, I specifically said the opposite. I suggested a minimal reproduction because I believed your problem was either somewhere else in your project, or unavoidable, and I still do. Second, I now feel pretty comfortable saying that you're doing things the same as any other Flash game, and whatever problems you see cannot be solved other than in perception. In the new links you posted, the animation looks perfectly smooth if I view it in the standalone SWF player, and has subtle flickering at the front and back edges in browsers (moreso in Firefox than in IE). Technically, I don't think it can improve (especially when it's basically perfect in the standalone player, implying that any choppiness in browsers is influenced by the container.)

Of course, the perceived performance can still improve. If the ship didn't contrast so sharply with the background, for example, the flicker would be much less noticeable. Also, simply making the ship move more slowly would make the movement appear much smoother, and could be combined with a moving background to give an illusion of greater speed (as one of your examples did).

As a sanity check, here's a similar minimal version I made in the IDE. http://www.fenomas.com/random/ship/ The performance is comparable to yours on my machine, and as I said, I really don't see any problem. (Except the occasional spike, which I now notice only occurs for me in Firefox.) Again, especially the fact that both versions appear basically perfect to me in the standalone player further convinces me that there's no golden algorithm here. I know that's not the answer you want, but it's the one I got.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...