function ping_pong_2d ( edrag, ecol, eg )

%*****************************************************************************80
%
%% ping_pong_2d() simulates the motion of a ping pong ball in 2D.
%
%  Discussion:
%
%    Verlet integration is used to simulate the change in position 
%    and velocity.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    08 September 2022
%
%  Author:
%
%    Algorithm by Nick Berry.
%    This version by John Burkardt.
%
%  Reference:
%
%    Nick Berry,
%    Verlet integration,
%    July 2018,
%    https://datagenetics.com/blog/july22018/index.html
%
%  Input:
%
%    real edrag, should be slightly less than 1 to simulate drag.
%
%    real ecol, should be slightly less than 1 to simulate energy
%    loss in collisions.
%
%    real eg, the gravitational acceleration.
%
  if ( nargin < 1 )
    edrag = 0.999;
  end

  if ( nargin < 2 )
    ecol = 0.90;
  end

  if ( nargin < 3 )
    eg = -0.05;
  end

  radius = 1.0;

  height = 7.0;
  width = 7.0;

  for step = 0 : 200

    if ( step == 0 )

      vx = 0.2 * randn ( );
      vy = 0.2 * randn ( );

      px = width * rand ( ) - vx;
      py = height * rand ( ) - vy;

    else

      vx = ( px - px_old ) * edrag;
      vy = ( py - py_old ) * edrag;

    end
%
%  Advance position.
%
    px_old = px;
    py_old = py;

    px = px + vx;
    py = py + vy + eg;
%
%  Adjust for horizontal collision.
%
    if ( ( width - radius ) < px )
      px = ( width - radius );
      px_old = px + vx;
      vx = ecol * ( px - px_old );
    elseif ( px < radius )
      px = radius;
      px_old = px + vx;
      vx = ecol * ( px - px_old );
    end
%
%  Adjust for vertical collision.
%
    if ( ( height - radius ) < py )
      py = ( height - radius );
      py_old = py + vy;
      vy = ecol * ( py - py_old );
    elseif ( py < radius )
      py = radius;
      py_old = py + vy;
      vy = ecol * ( py - py_old );
    end
%
%  Display.
%
    cla ( );
    axis ( 'equal' );
    grid ( 'on' );
    viscircles ( [px,py], radius );
    set ( gca, 'yticklabel', [] );
    axis ( [ 0.0, width, 0.0, height ] );
    pause ( 0.05 );
    
  end

  return
end

