Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am making a 2D game with simple "gravity": everything is just pulled toward 0,0. The speed at which they accelerate towards it is GravityAcceleration up to MaxGSpeed.

I also want the player to be able to pull these objects too. I'm using Magnitism and MaxSpeed to deal with the acceleration and speed at which the objects move towards the player.

However, it doesn't work, and I have no idea of what I'm doing wrong. The MoveToPlayer function is only called if the player is within 500 units of the object.

Can anyone see where I'm going wrong?

public virtual void Update(GameTime gameTime)
    var vectorToSun = new Vector2(0, 0) - Position;
    var distanceToCenter = vectorToSun.Length();

    _velocity += vectorToSun * GravityAcceleration * (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (_velocity.Length() > MaxGSpeed)
        _velocity *= MaxGSpeed;

    Position += _velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;

    rotation += 0.003f;

public void MoveToPlayer(Vector2 playerPos, GameTime gameTime)
    var vectorToPlayer = playerPos - Position;

    _velocity += vectorToPlayer * Magnitism * (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (_velocity.Length() > MaxSpeed)
        _velocity *= MaxSpeed;
share|improve this question
the 'MoveToPlayer' method looks sound. Sorry to state the obvious but are you calling it? Also, put a breakpoint somewhere toward the end of it and verify 'Position' & 'Magnitism' values are as expected. – Steve H Apr 29 '12 at 2:58
Are you sure you want to use 'TotalSeconds'? If youre calling the function each frame, shouldnt you use the time elapsed last frame? (I dont know the exact property name, i havent used xna before) – Aralox Apr 29 '12 at 5:53
@Aralox is definitely right!!! try some kind of ElapsedGameTime.FrameTime.. make sure this is (far) less than 1 (e.g. 0.01) if you're doing it on a per-frame basis. It can happen that your velocity is always "normalized" since it ought to be greater than your MaxSpeed threshold. – teodron Apr 30 '12 at 14:20
gameTime.ElapsedTime.TotalSeconds is correct. Note the ElapsedTime in that property chain. Total seconds means get the total number of seconds in the TimeSpan (as opposed to Seconds, which gets the whole number of seconds). The Timespan in that case is the ElapsedTime, i.e. time between frames. – George Duckett Apr 30 '12 at 14:26
What do you mean However, it doesn't work? Do objects not move toward the player? Do they move too fast? Do you get an exception? – Joshua Drake Apr 30 '12 at 15:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.