Box2D
view release on metacpan or search on metacpan
examples/pendulum.pl view on Meta::CPAN
# This example uses b2DistanceJoint to simulate a pendulum.
use strict;
use warnings;
use Box2D;
use SDL;
use SDL::Video;
use SDLx::App;
my $segments = $ARGV[0] || 2;
# The number of steps to apply to each frame,
# This seems to make joint correction lose less energy.
my $precision = 40;
# pixels
my $width = 450;
my $height = 450;
# pixels per meter
my $ppm = 30;
# meters per pixel
my $mpp = 1.0 / $ppm;
# frames per second
my $fps = 60.0;
my $timestep = 1.0 / $fps;
# velocity iterations
my $vIters = 8;
# position iterations
my $pIters = 8;
my $gravity = Box2D::b2Vec2->new( 0, -8.0 / $precision**2 );
# no sleep. don't lose energy.
my $world = Box2D::b2World->new( $gravity, 0 );
my $rodColor = 0x00CC70FF;
my $pathColor = 0xFFFFCFFF;
my $pivot = {
x0 => s2w( $width / 2 ),
y0 => s2w( $height / 2 ),
radius => s2w(4),
color => 0x5CCC00FF,
};
$pivot->{body} = make_static_circle( @$pivot{qw( x0 y0 radius )} );
$pivot->{anchor} = Box2D::b2Vec2->new( @$pivot{qw( x0 y0 )} );
my $prev_pivot = $pivot;
my @bobs;
for ( 1 .. $segments ) {
my $bob = {
y0 => s2w( $height / 2 + .9 * $height * $_ / ( 2 * $segments ) ),
x0 => s2w( $width / 2 + 1 ),
radius => s2w(6),
color => 0xCC005CFF,
};
$bob->{body} = make_dynamic_circle( @$bob{qw( x0 y0 radius )} );
$bob->{anchor} = Box2D::b2Vec2->new( @$bob{qw( x0 y0 )} );
my $jointDef = Box2D::b2DistanceJointDef->new();
$jointDef->Initialize(
$prev_pivot->{body}, $bob->{body},
$prev_pivot->{anchor}, $bob->{anchor}
);
# high frequency means less energy lost from joint correction
$jointDef->frequencyHz( 1 / $timestep );
$jointDef->dampingRatio(0);
$world->CreateJoint($jointDef);
$prev_pivot = $bob;
push @bobs, $bob;
}
my $app = SDLx::App->new(
width => $width,
height => $height,
dt => $timestep,
min_t => $timestep / 2,
flags => SDL_DOUBLEBUF | SDL_HWSURFACE,
eoq => 1,
);
my $bg = $app->duplicate;
$bg->draw_rect( [ 0, 0, $width, $height ], [ 0, 0, 0, 255 ] );
my $realFps = $fps;
my $frames = 1;
( run in 1.278 second using v1.01-cache-2.11-cpan-71847e10f99 )