feat: clampLength for Vector2 extension (#2190)

With this method you can clamp the length of a vector, instead fitting it in a box like clamp and clampScalar does.
This commit is contained in:
Lukas Klingsbo
2022-11-25 15:36:18 +01:00
committed by GitHub
parent e289f118ee
commit 51a896b2c8
3 changed files with 38 additions and 0 deletions

View File

@ -32,6 +32,7 @@ class IsometricTileMapExample extends FlameGame with MouseMovementDetector {
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
debugMode = true;
final tilesetImage = await images.load('tile_maps/tiles$suffix.png'); final tilesetImage = await images.load('tile_maps/tiles$suffix.png');
final tileset = SpriteSheet( final tileset = SpriteSheet(
image: tilesetImage, image: tilesetImage,

View File

@ -80,6 +80,21 @@ extension Vector2Extension on Vector2 {
} }
} }
/// Clamps the [length] of this vector.
///
/// This means that if the length is less than [min] the length will be set to
/// [min] and if the length is larger than [max], the length will be set to
/// [max]. If the length is in between [min] and [max], no changes will be
/// made.
void clampLength(double min, double max) {
final lengthSquared = length2;
if (lengthSquared > max * max) {
scaleTo(max);
} else if (lengthSquared < min * min) {
scaleTo(min);
}
}
/// Project this onto [other]. /// Project this onto [other].
/// ///
/// [other] needs to have a length > 0; /// [other] needs to have a length > 0;

View File

@ -213,6 +213,28 @@ void main() {
}); });
}); });
group('clampLength', () {
test('clamp length min', () {
final v = Vector2(1, 0)..clampLength(2.0, 3.0);
expect(v.length, 2.0);
});
test('clamp length max', () {
final v = Vector2(1, 0)..clampLength(0.5, 0.8);
expect(v.length, 0.8);
});
test('clamp negative vector', () {
final v = Vector2(-1, -1)..clampLength(0.5, 0.8);
expect(v.length, 0.8);
});
test('no effect on vector in range', () {
final v = Vector2(1, 0)..clampLength(0.5, 2.0);
expect(v.length, 1.0);
});
});
group('projection', () { group('projection', () {
test('Project onto longer vector', () { test('Project onto longer vector', () {
final u = Vector2(5, 2); final u = Vector2(5, 2);