Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add reusable vector to the Vector2 extension #2429

Merged
merged 10 commits into from
Mar 26, 2023
23 changes: 20 additions & 3 deletions packages/flame/lib/src/extensions/vector2.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ import 'package:vector_math/vector_math_64.dart';
export 'package:vector_math/vector_math_64.dart' hide Colors;

extension Vector2Extension on Vector2 {
/// This is a reusable vector that can be used within the [Vector2Extension]
/// to avoid creation of new Vector2 instances.
///
/// Avoid using this in async extension methods, as it can lead to race
/// conditions.
static final _reusableVector = Vector2.zero();

/// Creates an [Offset] from the [Vector2]
Offset toOffset() => Offset(x, y);

Expand All @@ -31,7 +38,13 @@ extension Vector2Extension on Vector2 {

/// Linearly interpolate towards another Vector2
void lerp(Vector2 to, double t) {
setFrom(this + (to - this) * t);
setFrom(
_reusableVector
..setFrom(to)
..sub(this)
..scale(t)
..add(this),
);
}

/// Whether the [Vector2] is the zero vector or not
Expand Down Expand Up @@ -128,7 +141,10 @@ extension Vector2Extension on Vector2 {
double ds,
) {
if (this != target) {
final diff = target - this;
final diff = _reusableVector
..setFrom(target)
..sub(this);

if (diff.length < ds) {
setFrom(target);
} else {
Expand All @@ -149,7 +165,8 @@ extension Vector2Extension on Vector2 {
/// Down: Vector(0.0, 1.0).screenAngle == +-pi
/// Left: Vector(-1.0, 0.0).screenAngle == -pi/2
/// Right: Vector(-1.0, 0.0).screenAngle == pi/2
double screenAngle() => (clone()..y *= -1).angleToSigned(Vector2(0.0, 1.0));
double screenAngle() => (_reusableVector..setValues(x, y * (-1)))
.angleToSigned(Vector2(0.0, 1.0));

/// Modulo/Remainder
Vector2 operator %(Vector2 mod) => Vector2(x % mod.x, y % mod.y);
Expand Down