Advertisement
Guest User

movement.pl

a guest
Jun 10th, 2012
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.72 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3. use SDL;
  4. use SDLx::App;
  5. use SDLx::Rect;
  6. use SDL::Events;
  7. use SDL::Event;
  8.  
  9.  
  10. my $app=SDLx::App->new(w=>800,h=>600,title=>"Movement!",d=>32,exit_on_quit=>1);
  11.  
  12. #The rectangle that we'll be moving around.
  13. my $rect=SDLx::Rect->new(200,200,40,40);
  14.  
  15. #x and y velocities.
  16. #For simplicity's sake, we'll have zero acceleration.
  17. my $v_x=0;
  18. my $v_y=0;
  19.  
  20. #Basic rendering handler.
  21. $app->add_show_handler(sub{
  22.     $app->draw_rect([0,0,$app->width,$app->height],[0,0,0,255]);
  23.     $app->draw_rect($rect,[0,0,255,255]);
  24.     $app->update;
  25.     }
  26. ); 
  27.  
  28.  
  29. $app->add_event_handler(sub{
  30.     my ($event,$app)=@_;
  31.  
  32.     #Set velocity equal to plus or minus 2 depending on ASWD direction.
  33.     if($event->type == SDL_KEYDOWN)
  34.     {
  35.         my $key= lc(SDL::Events::get_key_name($event->key_sym));
  36.  
  37.         if($key eq 'a')
  38.         {
  39.             $v_x=-2;
  40.         }
  41.         elsif($key eq 'd')
  42.         {
  43.             $v_x=2;
  44.         }
  45.         elsif($key eq 'w')
  46.         {
  47.             $v_y=2;
  48.         }
  49.         elsif($key eq 's')
  50.         {
  51.             $v_y=-2;
  52.         }
  53.     }
  54.     elsif($event->type == SDL_KEYUP) #Reset velocity if key is released.
  55.     {
  56.         my $key= lc(SDL::Events::get_key_name($event->key_sym));   
  57.         if($key eq 'a' or $key eq 'd')
  58.         {
  59.             $v_x=0;
  60.         }
  61.         elsif($key eq 'w' or $key eq 's')
  62.         {
  63.             $v_y=0;
  64.         }
  65.     }  
  66. });
  67.  
  68. #Quit when "q" is pressed.
  69. $app->add_event_handler(sub{
  70.     my $event=shift;
  71.     if($event->type == SDL_KEYDOWN)
  72.     {
  73.         if(lc(SDL::Events::get_key_name($event->key_sym)) eq 'q')
  74.         {
  75.             $app->stop;
  76.         }
  77.     }
  78. });
  79.  
  80.  
  81. $app->add_move_handler(\&move);
  82.  
  83. sub move
  84. {
  85.     my ($step,$app,$t)=@_;
  86.     return unless $step;
  87.  
  88.     #Gather x and y coordinates of rectangle.
  89.     my $x=$rect->x;
  90.     my $y=$rect->y;
  91.  
  92.     #Adjust positions accordingly.
  93.     $x+=$v_x * $step;
  94.     $y-=$v_y * $step;
  95.  
  96.     #Set new coordinates.
  97.     $rect->x($x);
  98.     $rect->y($y);
  99.    
  100.     #Debugging, to figure out WTF is going on.
  101.     #print "$v_x,$v_y,$t\n";
  102. }  
  103.  
  104. $app->run();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement