Skip to content

Commit

Permalink
refactor: Use a temp vector for delta calculations of FollowBehavior (
Browse files Browse the repository at this point in the history
#3230)

This PR add a temp vector in `FollowBehavior` to avoid creating a new
vector every frame for the delta calculations.
  • Loading branch information
ufrshubham authored Jul 21, 2024
1 parent 380d6aa commit 524793d
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions packages/flame/lib/src/camera/behaviors/follow_behavior.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'package:flame/src/camera/viewport.dart';
import 'package:flame/src/components/core/component.dart';
import 'package:flame/src/components/position_component.dart';
import 'package:flame/src/effects/provider_interfaces.dart';
import 'package:vector_math/vector_math_64.dart';

/// This behavior will make the [owner] follow the [target].
///
Expand Down Expand Up @@ -46,6 +47,8 @@ class FollowBehavior extends Component {
final bool horizontalOnly;
final bool verticalOnly;

final _tempDelta = Vector2.zero();

@override
void onMount() {
if (_owner == null) {
Expand All @@ -59,19 +62,18 @@ class FollowBehavior extends Component {

@override
void update(double dt) {
final delta = target.position - owner.position;
if (horizontalOnly) {
delta.y = 0;
}
if (verticalOnly) {
delta.x = 0;
}
final distance = delta.length;
if (distance > _speed * dt) {
delta.scale(_speed * dt / distance);
_tempDelta.setValues(
verticalOnly ? 0 : target.position.x - owner.position.x,
horizontalOnly ? 0 : target.position.y - owner.position.y,
);

final distance = _tempDelta.length;
final deltaOffset = _speed * dt;
if (distance > deltaOffset) {
_tempDelta.scale(deltaOffset / distance);
}
if (delta.x != 0 || delta.y != 0) {
owner.position = delta..add(owner.position);
if (_tempDelta.x != 0 || _tempDelta.y != 0) {
owner.position = _tempDelta..add(owner.position);
}
}
}

0 comments on commit 524793d

Please sign in to comment.