/
spring1
executable file
·63 lines (52 loc) · 1.14 KB
/
spring1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env perl
use strict;
use warnings;
use SDL;
use SDL::Event;
use SDLx::App;
my $app = SDLx::App->new(
width => 400,
height => 400,
title => 'Spring');
my $spring = 0.05;
my $friction = 0.05;
my $target = {
x => $app->w/2,
y => $app->h/2,
};
my $ball = {
x => 0,
y => 0,
r => 10,
vx => 0,
vy => 0,
ax => 0,
ay => 0,
};
$app->add_event_handler(\&event);
$app->add_move_handler (\&calc);
$app->add_show_handler (\&render);
$app->run();
sub event {
my $event = shift;
my $controller = shift;
$controller->stop if $event->type == SDL_QUIT;
}
sub calc {
my ($step, $app) = @_;
$ball->{ax} = ($target->{x} - $ball->{x}) * $spring;
$ball->{ay} = ($target->{y} - $ball->{y}) * $spring;
$ball->{vx} += $ball->{ax} * $step;
$ball->{vy} += $ball->{ay} * $step;
$ball->{vx} *= 1 - $friction * $step;
$ball->{vy} *= 1 - $friction * $step;
$ball->{x} += $ball->{vx} * $step;
$ball->{y} += $ball->{vy} * $step;
}
sub render {
my ($delta, $app) = @_;
$app->draw_rect([0, 0, $app->w, $app->h], 0); # clear screen
$app->draw_circle_filled([$ball->{x}, $ball->{y}], $ball->{r},
[255, 0, 0, 255]);
$app->update();
}