feat: Add initial version of behavior_tree and flame_behavior_tree package (#3045)

First pass on adding behavior tree for flame. This PR adds 2 packages:

- behavior_tree: A pure dart implementation of behavior tree.
- flame_behavior_tree: A bridge package that integrates behavior_tree
with flame.

Demo: 


https://github.com/flame-engine/flame/assets/33748002/1d2b00ab-1b6e-406e-9052-a24370c8f1ab
This commit is contained in:
DevKage
2024-03-10 21:59:15 +05:30
committed by GitHub
parent f49d24c02d
commit faf2df4b8c
36 changed files with 1554 additions and 0 deletions

View File

@ -0,0 +1,57 @@
import 'dart:async';
import 'package:behavior_tree/behavior_tree.dart';
import 'package:flame/components.dart';
import 'package:flutter/foundation.dart';
/// A mixin on [Component] to indicate that the component has a behavior tree.
///
/// Reference to the behavior tree for this component can be set or accessed
/// via [treeRoot]. The update frequency of the tree can be reduced by
/// increasing [tickInterval]. By default, the tree will be updated on every
/// update of the component.
mixin HasBehaviorTree<T extends NodeInterface> on Component {
T? _treeRoot;
Timer? _timer;
double _tickInterval = 0;
/// The delay between any two ticks of the behavior tree.
double get tickInterval => _tickInterval;
set tickInterval(double interval) {
_tickInterval = interval;
if (_tickInterval > 0) {
_timer ??= Timer(interval, repeat: true);
_timer?.limit = interval;
} else {
_timer?.onTick = null;
_timer = null;
_tickInterval = 0;
}
}
/// The root node of the behavior tree.
T get treeRoot => _treeRoot!;
set treeRoot(T value) {
_treeRoot = value;
_timer?.onTick = _treeRoot!.tick;
}
@override
@mustCallSuper
Future<void> onLoad() async {
super.onLoad();
_timer?.onTick = _treeRoot?.tick;
}
@override
@mustCallSuper
void update(double dt) {
super.update(dt);
if (_tickInterval > 0) {
_timer?.update(dt);
} else {
_treeRoot?.tick();
}
}
}