Moving Dynamic Bodies

Dec 31, 2011 at 6:08 AM

Hey all,

I have a really simple problem, but for the life of me I have been beating my head against a wall for 2-3 coding sessions (typically a few hours) in a row. I think I have found the root of my problem, but I just don't know how to do it differently. What I am trying to do is simply move a dynamic body from point A to point B.

If I start the body where it needs positive values to reach its destination it works perfectly (other than overshooting the location, but I knew that was going to happen). If the body needs a negative value (e.g. in XNA to go UP from the BOTTOM of the screen) however the enemy does not move. I believe this is because linearVelocity's vector2(s) will not be negative? 

Below is the code for moving the body.

 

        public virtual void Update(GameTime gameTime)
        {
            Vector2 pixelPos = ConvertUnits.ToDisplayUnits(this.body.Position);
            if (!isDestroyed)
            {
                if (autoRotate)
                    this.body.Rotation = (float)Math.Atan2(
                        pixelPos.Y - lastLocation.Y,
                        pixelPos.X - lastLocation.X);
                sprite.Update(gameTime);
                lastLocation = ConvertUnits.ToDisplayUnits(this.body.Position);
                move();
            }
        }

        private void move()
        {
            Vector2 maxVelocity;
            Vector2 heading =  endLocation - ConvertUnits.ToDisplayUnits(this.body.Position);
            heading.Normalize();
            insideLoop = false;
            float vX = 0f;
            float vY = 0f;
            if (heading == Vector2.Zero)
                this.body.LinearVelocity = Vector2.Zero;
            if (heading != Vector2.Zero && endLocation != Vector2.Zero)
            {
// this.linearVelocity is a float defining the max speed.
                maxVelocity = heading * this.linearVelocity;
                if (this.body.LinearVelocity.X < maxVelocity.X)
                    vX = heading.X * this.acceleration;
                if (this.body.LinearVelocity.Y < maxVelocity.Y)
                    vY = heading.Y * this.acceleration;

                this.body.LinearVelocity += new Vector2(vX, vY);
            }
        }

Am I just taking the wrong approach to trying to move a dynamic body?

Dec 31, 2011 at 6:56 PM

Ignore the above. I figured it out. 

                if (this.body.LinearVelocity.X < maxVelocity.X)
                    vX = heading.X * this.acceleration;
                if (this.body.LinearVelocity.Y < maxVelocity.Y)
                    vY = heading.Y * this.acceleration;

needed to be:
                if (Math.Abs(this.body.LinearVelocity.X) < Math.Abs(maxVelocity.X))
                    vX = heading.X * this.acceleration;
                if (Math.Abs(this.body.LinearVelocity.Y) < Math.Abs(maxVelocity.Y))
                    vY = heading.Y * this.acceleration;