/
bouncing_ball_example.dart
105 lines (90 loc) · 2.34 KB
/
bouncing_ball_example.dart
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import 'dart:math' as math;
import 'dart:ui';
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
class BouncingBallExample extends FlameGame with HasCollisionDetection {
static const description = '''
This example shows how you can use the Collisions detection api to know when a ball
collides with the screen boundaries and then update it to bounce off these boundaries.
''';
@override
void onLoad() {
addAll([
ScreenHitbox(),
Ball(),
]);
}
}
class Ball extends CircleComponent
with HasGameRef<FlameGame>, CollisionCallbacks {
late Vector2 velocity;
Ball() {
paint = Paint()..color = Colors.white;
radius = 10;
}
static const double speed = 500;
static const degree = math.pi / 180;
@override
Future<void> onLoad() async {
super.onLoad();
_resetBall;
final hitBox = CircleHitbox(
radius: radius,
);
addAll([
hitBox,
]);
}
@override
void update(double dt) {
super.update(dt);
position += velocity * dt;
}
void get _resetBall {
position = gameRef.size / 2;
final spawnAngle = getSpawnAngle;
final vx = math.cos(spawnAngle * degree) * speed;
final vy = math.sin(spawnAngle * degree) * speed;
velocity = Vector2(
vx,
vy,
);
}
double get getSpawnAngle {
final random = math.Random().nextDouble();
final spawnAngle = lerpDouble(0, 360, random)!;
return spawnAngle;
}
@override
void onCollisionStart(
Set<Vector2> intersectionPoints,
PositionComponent other,
) {
super.onCollisionStart(intersectionPoints, other);
if (other is ScreenHitbox) {
final collisionPoint = intersectionPoints.first;
// Left Side Collision
if (collisionPoint.x == 0) {
velocity.x = -velocity.x;
velocity.y = velocity.y;
}
// Right Side Collision
if (collisionPoint.x == gameRef.size.x) {
velocity.x = -velocity.x;
velocity.y = velocity.y;
}
// Top Side Collision
if (collisionPoint.y == 0) {
velocity.x = velocity.x;
velocity.y = -velocity.y;
}
// Bottom Side Collision
if (collisionPoint.y == gameRef.size.y) {
velocity.x = velocity.x;
velocity.y = -velocity.y;
}
}
}
}