/examples/SDLx/SDLx_C_Interface.pl

http://github.com/PerlGameDev/SDL · Perl · 65 lines · 38 code · 17 blank · 10 comment · 2 complexity · 0f72f2091765c164fed76ea0b427a2b0 MD5 · raw file

  1. use strict;
  2. use warnings;
  3. use Time::HiRes qw( time sleep );
  4. use SDL;
  5. use SDLx::App;
  6. use SDL::Event;
  7. use SDL::Events;
  8. use SDLx::Controller::Interface;
  9. my $app = SDLx::App->new( w => 200, h => 200, title => "timestep", delay => 10 );
  10. #The initial x and y for this object.
  11. my $spring = SDLx::Controller::Interface->new( x => 100, y => 100 );
  12. #we have a constant x velocity of 20
  13. my $constant = SDLx::Controller::Interface->new( x => 0, y => 20, v_x => 20 );
  14. #NO need to send an acceleration for x,y or rotation
  15. $constant->set_acceleration( sub { return ( 0, 0, 0 ) } );
  16. #a hooke's law acceleration for the spring
  17. my $accel = sub {
  18. my ( $t, $state ) = @_;
  19. my $k = 10;
  20. my $b = 1;
  21. my $ax = ( ( -1 * $k ) * ( $state->x ) - $b * $state->v_x );
  22. return ( $ax, 0, 0 );
  23. };
  24. $spring->set_acceleration($accel);
  25. #This is how we will render the spring. Notice the x, and y are not tied to how they will show on the screen
  26. my $render = sub {
  27. my $state = shift;
  28. $app->draw_rect( [ 100 - $state->x, $state->y, 2, 2 ], 0xFF0FFF );
  29. };
  30. #an event handler to exit
  31. my $event = sub {
  32. $_[1]->stop if $_[0]->type == SDL_QUIT;
  33. };
  34. $app->add_event_handler($event);
  35. #clear the screen
  36. $app->add_show_handler( sub { $app->draw_rect( [ 0, 0, $app->w, $app->h ], 0x000000 ) } );
  37. #add the spring
  38. $spring->attach($app, $render );
  39. #add the constant_velocity
  40. $constant->attach( $app,
  41. sub {
  42. my $state = shift;
  43. $app->draw_rect( [ $state->x, $state->y, 4, 4 ], 0xFFFFFF );
  44. }
  45. );
  46. #add the final update
  47. $app->add_show_handler( sub { $app->update() } );
  48. $app->run();