I've decided that it's best to start using vectors in my games instead of the
xPos += xSpeed and yPos += ySpeed approach.

I'm posting some of the code from my basic model class which handles movement logic in my game so that someone can tell me if I am using vectors correctly. I have a position, direction, acceleration and velocity vector. Here is some code, I can post more if needed:

model.update() and rotate() function

public function update():void
    dispatchEvent(new Event(Event.CHANGE));

public function rotate(val:Number):void
    angle += val;
    direction.x = Math.cos(angle * degreesToRads);
    direction.y = Math.sin(angle * degreesToRads);

and the checkInput() function

private function checkKeys():void 
    accel.set(0, 0);
        rotate( -5);
    if (keys[Keyboard.RIGHT])
    if (keys[Keyboard.UP])
        accel.x = direction.x * 0.8;
        accel.y = direction.y * 0.8;
    if (keys[Keyboard.DOWN])
        accel.x = direction.x * 0.5;
        accel.y = direction.y * 0.5;

Hopefully someone can tell me if I'm using vectors correctly by adding acceleration to velocity and to speed and also if I'm doing rotation the correct way or if there is a better way. Or anything anyone can suggest to improve would be great.

  • 3
    \$\begingroup\$ Come on guys down votes with no comment are not helpful. \$\endgroup\$ – James Jan 25 '12 at 0:23
  • 2
    \$\begingroup\$ There is no specific question here. \$\endgroup\$ – Tetrad Jan 25 '12 at 15:31

There's no "correct" way to do this. Using xPos += xSpeed and yPos += ySpeed is basically the same as pos.addVec(velocity). I suggest you use what you're comfortable with.

If movement behaves as it should, then go ahead. Some minor things you could improve, by looking at your code:

  • Events are slow. Don't dispatch them in the update loop... call methods directly or use signals.
  • You should calculate movement in a framerate independent fashion, so that your game runs at the same speed on slower computers as well. The way to do this would be to measure the elapsed time since the last frame and use this delta for movement calculation.
  • You don't need to normalize your direction after the rotation calculation. It's a unit vector already.
  • \$\begingroup\$ I take minor issue with your first bullet point, because it's unclear from the code shown exactly what happens as a result of "dispatchEvent" and consequently it seems unreasonable to diagnose it as "slow." \$\endgroup\$ – user1430 Jan 25 '12 at 16:48
  • \$\begingroup\$ @JoshPetrie It's true that the amount of time for event dispatching and handling might not be significant. Compared to other approaches like signals, events are a bad choice though. They are slower (here's a comparison of turbosignals, as3signals and native events) cumbersome and prone to memory leaks (see this article). \$\endgroup\$ – bummzack Jan 25 '12 at 16:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.