Q:

pacman grid movement

private bool MoveTowardsPoint(Vector2 goal, float elapsed)
{
    // If we're already at the goal return immediatly
    if (_position == goal) return true;

    // Find direction from current position to goal
    Vector2 direction = Vector2.Normalize(goal - _position);

    // Move in that direction
    _position += direction * Speed * elapsed;

    // If we moved PAST the goal, move it back to the goal
    if (Math.Abs(Vector2.Dot(direction, Vector2.Normalize(goal - _position)) + 1) < 0.1f)
        _position = goal;

    // Return whether we've reached the goal or not
    return _position == goal;
}
0
// Detect user input and set direction
if (Keyboard.GetState().IsKeyDown(Keys.Down)) _direction = new Vector2(0, 1);
if (Keyboard.GetState().IsKeyDown(Keys.Right)) _direction = new Vector2(1, 0);
if (Keyboard.GetState().IsKeyDown(Keys.Up)) _direction = new Vector2(0, -1);
if (Keyboard.GetState().IsKeyDown(Keys.Left)) _direction = new Vector2(-1, 0);

// If there's no target and we can move in the chosen direction, set new target to be the next tile
if (_target == null)
    if (CanMoveInDirection(_position, _direction))
        _target = _position + _direction * 32;

// If there's a target, then move pacman towards that location, and clear target when destination is reached
if (_target != null)
    if (MoveTowardsPoint(_target.Value, (float) gameTime.ElapsedGameTime.TotalSeconds))
        _target = null;
0
private Vector2 _position = new Vector2(32, 32);
private const float Speed = 156;
private Vector2 _direction = new Vector2(0, 1);
private Vector2? _target;
0

New to Communities?

Join the community