use strict;
use warnings;
use SDL;
use SDLx::App;
use SDLx::Rect;
use SDL::Events;
use SDL::Event;
my $app=SDLx::App->new(w=>800,h=>600,title=>"Movement!",d=>32,exit_on_quit=>1);
#The rectangle that we'll be moving around.
my $rect=SDLx::Rect->new(200,200,40,40);
#x and y velocities.
#For simplicity's sake, we'll have zero acceleration.
my $v_x=0;
my $v_y=0;
#Basic rendering handler.
$app->add_show_handler(sub{
$app->draw_rect([0,0,$app->width,$app->height],[0,0,0,255]);
$app->draw_rect($rect,[0,0,255,255]);
$app->update;
}
);
$app->add_event_handler(sub{
my ($event,$app)=@_;
#Set velocity equal to plus or minus 2 depending on ASWD direction.
if($event->type == SDL_KEYDOWN)
{
my $key= lc(SDL::Events::get_key_name($event->key_sym));
if($key eq 'a')
{
$v_x=-2;
}
elsif($key eq 'd')
{
$v_x=2;
}
elsif($key eq 'w')
{
$v_y=2;
}
elsif($key eq 's')
{
$v_y=-2;
}
}
elsif($event->type == SDL_KEYUP) #Reset velocity if key is released.
{
my $key= lc(SDL::Events::get_key_name($event->key_sym));
if($key eq 'a' or $key eq 'd')
{
$v_x=0;
}
elsif($key eq 'w' or $key eq 's')
{
$v_y=0;
}
}
});
#Quit when "q" is pressed.
$app->add_event_handler(sub{
my $event=shift;
if($event->type == SDL_KEYDOWN)
{
if(lc(SDL::Events::get_key_name($event->key_sym)) eq 'q')
{
$app->stop;
}
}
});
$app->add_move_handler(\&move);
sub move
{
my ($step,$app,$t)=@_;
return unless $step;
#Gather x and y coordinates of rectangle.
my $x=$rect->x;
my $y=$rect->y;
#Adjust positions accordingly.
$x+=$v_x * $step;
$y-=$v_y * $step;
#Set new coordinates.
$rect->x($x);
$rect->y($y);
#Debugging, to figure out WTF is going on.
#print "$v_x,$v_y,$t\n";
}
$app->run();