diff --git a/analysis_options.yaml b/analysis_options.yaml index 946826280..70955574d 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -2,7 +2,10 @@ include: package:flame_lint/analysis_options.yaml analyzer: errors: + avoid_bool_literals_in_conditional_expressions: ignore avoid_catches_without_on_clauses: ignore + avoid_positional_boolean_parameters: ignore + comment_references: ignore use_if_null_to_convert_nulls_to_bools: ignore exclude: - 'example/**' \ No newline at end of file diff --git a/example/lib/shared/decoration/spikes.dart b/example/lib/shared/decoration/spikes.dart index bfacbca58..d74ac985e 100644 --- a/example/lib/shared/decoration/spikes.dart +++ b/example/lib/shared/decoration/spikes.dart @@ -9,7 +9,7 @@ class Spikes extends GameDecoration with Sensor { position: position, size: size ?? Vector2.all(DungeonMap.tileSize / 1.5), ) { - setSensorInterval(500); + sensorInterval = 500; } @override diff --git a/lib/background/background_image_game.dart b/lib/background/background_image_game.dart index 7589b0d2c..732ee90aa 100644 --- a/lib/background/background_image_game.dart +++ b/lib/background/background_image_game.dart @@ -9,6 +9,8 @@ /// /// Rafaelbarbosatec /// on 30/11/21 +library; + import 'package:bonfire/bonfire.dart'; import 'package:bonfire/camera/bonfire_camera.dart'; import 'package:bonfire/map/util/map_assets_manager.dart'; @@ -48,8 +50,8 @@ class BackgroundImageGame extends GameBackground with UseSprite { if (camera.position != _lastPosition) { _lastPosition = camera.position.clone(); position = _parallaxOffset.translated( - (camera.position.x * -(parallaxX / camera.zoom)), - (camera.position.y * -(parallaxY / camera.zoom)), + camera.position.x * -(parallaxX / camera.zoom), + camera.position.y * -(parallaxY / camera.zoom), ); } } diff --git a/lib/base/base_game.dart b/lib/base/base_game.dart index 84b4dbedf..ea5952898 100644 --- a/lib/base/base_game.dart +++ b/lib/base/base_game.dart @@ -23,7 +23,7 @@ abstract class BaseGame extends FlameGame @override void updateTree(double dt) { _gesturesComponents = [...world.children, ...camera.viewport.children] - .where((c) => _hasGesture(c)) + .where(_hasGesture) .cast(); super.updateTree(dt); } @@ -38,7 +38,9 @@ abstract class BaseGame extends FlameGame @override void onPointerCancel(PointerCancelEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerCancel(event)) { return; @@ -48,7 +50,9 @@ abstract class BaseGame extends FlameGame @override void onPointerUp(PointerUpEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerUp(event)) { return; @@ -58,7 +62,9 @@ abstract class BaseGame extends FlameGame @override void onPointerMove(PointerMoveEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerMove(event)) { return; @@ -68,7 +74,9 @@ abstract class BaseGame extends FlameGame @override void onPointerDown(PointerDownEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerDown(event)) { return; @@ -78,7 +86,9 @@ abstract class BaseGame extends FlameGame @override void onPointerHover(PointerHoverEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerHover(event)) { return; @@ -88,7 +98,9 @@ abstract class BaseGame extends FlameGame @override void onPointerSignal(PointerSignalEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerSignal(event)) { return; @@ -101,11 +113,11 @@ abstract class BaseGame extends FlameGame KeyEvent event, Set keysPressed, ) { - KeyEventResult result = KeyEventResult.ignored; + var result = KeyEventResult.ignored; if (!enabledKeyboard) { return result; } - for (var listener in _keyboardComponents) { + for (final listener in _keyboardComponents) { if (listener.onKeyboard(event, keysPressed)) { result = KeyEventResult.handled; } @@ -115,7 +127,7 @@ abstract class BaseGame extends FlameGame /// Verify if the Component contain gestures. bool _hasGesture(Component c) { - return ((c is GameComponent && c.isVisible)) && ((c).hasGesture()); + return (c is GameComponent && c.isVisible) && (c.hasGesture()); } @override diff --git a/lib/base/bonfire_game_interface.dart b/lib/base/bonfire_game_interface.dart index c89fcd139..4f94ecd89 100644 --- a/lib/base/bonfire_game_interface.dart +++ b/lib/base/bonfire_game_interface.dart @@ -4,7 +4,6 @@ import 'package:bonfire/bonfire.dart'; import 'package:bonfire/camera/bonfire_camera.dart'; import 'package:bonfire/color_filter/color_filter_component.dart'; import 'package:bonfire/lighting/lighting_component.dart'; -import 'package:flame/game.dart'; // ignore: implementation_imports import 'package:flame/src/game/overlay_manager.dart'; import 'package:flutter/widgets.dart'; @@ -40,23 +39,6 @@ abstract class BonfireGameInterface { SceneBuilderStatus sceneBuilderStatus = SceneBuilderStatus(); double timeScale = 1.0; - /// A property that stores an [ActiveOverlaysNotifier] - /// - /// This is useful to render widgets above a game, like a pause menu for - /// example. - /// Overlays visible or hidden via [overlays].add or [overlays].remove, - /// respectively. - /// - /// Ex: - /// ``` - /// final pauseOverlayIdentifier = 'PauseMenu'; - /// overlays.add(pauseOverlayIdentifier); // marks 'PauseMenu' to be rendered. - /// overlays.remove(pauseOverlayIdentifier); // marks 'PauseMenu' to not be rendered. - /// ``` - /// - /// See also: - /// - GameWidget - /// - [Game.overlayManager] // ignore: invalid_use_of_internal_member OverlayManager get overlays; diff --git a/lib/base/game_component.dart b/lib/base/game_component.dart index e2bcfe6d1..3ab788526 100644 --- a/lib/base/game_component.dart +++ b/lib/base/game_component.dart @@ -12,7 +12,7 @@ abstract class GameComponent extends PositionComponent InternalChecker, HasPaint, CollisionCallbacks { - final String _keyIntervalCheckIsVisible = "CHECK_VISIBLE"; + final String _keyIntervalCheckIsVisible = 'CHECK_VISIBLE'; final int _intervalCheckIsVisible = 100; Map? properties; @@ -22,7 +22,14 @@ abstract class GameComponent extends PositionComponent /// Param checks if this component is visible on the screen bool _isVisibleInScreen = false; - bool get isVisible => _visible ? _isVisibleInScreen : false; + bool get isVisible { + if (_visible) { + return _isVisibleInScreen; + } + + return false; + } + set isVisible(bool visible) { _visible = visible; } @@ -67,7 +74,9 @@ abstract class GameComponent extends PositionComponent } void _checkIsVisible(double dt) { - if (!enabledCheckIsVisible) return; + if (!enabledCheckIsVisible) { + return; + } if (checkInterval( _keyIntervalCheckIsVisible, _intervalCheckIsVisible, @@ -90,7 +99,10 @@ abstract class GameComponent extends PositionComponent /// Method that checks if this component is visible on the screen @mustCallSuper bool isVisibleInCamera() { - return hasGameRef ? gameRef.isVisibleInCamera(this) : false; + if (hasGameRef) { + return gameRef.isVisibleInCamera(this); + } + return false; } @override @@ -101,8 +113,10 @@ abstract class GameComponent extends PositionComponent } void _onSetIfVisible() { - if (!_visible) return; - bool nowIsVisible = isVisibleInCamera(); + if (!_visible) { + return; + } + var nowIsVisible = isVisibleInCamera(); if (isHud) { nowIsVisible = true; enabledCheckIsVisible = false; @@ -134,7 +148,7 @@ abstract class GameComponent extends PositionComponent void _confHitBoxRender(Component component) { if (component is ShapeHitbox) { if (gameRef.showCollisionArea) { - var paintCollition = Paint() + final paintCollition = Paint() ..color = gameRef.collisionAreaColor ?? const Color(0xffffffff); if (this is Sensor) { paintCollition.color = Sensor.color; @@ -153,7 +167,7 @@ abstract class GameComponent extends PositionComponent Rect get rectCollision { if (_rectCollision == null) { - var list = children.query(); + final list = children.query(); if (list.isNotEmpty) { _rectCollision = list.fold( list.first.toRect(), @@ -163,7 +177,7 @@ abstract class GameComponent extends PositionComponent ); } } - var absoluteRect = toAbsoluteRect(); + final absoluteRect = toAbsoluteRect(); if (_rectCollision != null) { return _rectCollision!.translate(absoluteRect.left, absoluteRect.top); @@ -245,7 +259,7 @@ abstract class GameComponent extends PositionComponent } List _getSensorsHitbox() { - var sensorHitBox = []; + final sensorHitBox = []; gameRef.query(onlyVisible: true).forEach((e) { sensorHitBox.addAll(e.children.query()); }); diff --git a/lib/base/listener_game_widget.dart b/lib/base/listener_game_widget.dart index 411af5df2..43d2de427 100644 --- a/lib/base/listener_game_widget.dart +++ b/lib/base/listener_game_widget.dart @@ -32,8 +32,8 @@ typedef GameFactory = T Function(); class ListenerGameWidget extends StatefulWidget { /// The game instance which this widget will render, if the normal constructor /// is used. - /// If the [ListenerGameWidget.controlled] constructor is used, this will always be - /// `null`. + /// If the [ListenerGameWidget.controlled] constructor is used, this will + /// aways be `null`. final T? game; /// A function that creates a [Game] that this widget will render. @@ -121,8 +121,8 @@ class ListenerGameWidget extends StatefulWidget { /// game.overlays.add('PauseMenu'); /// ``` ListenerGameWidget({ - Key? key, required T this.game, + super.key, this.textDirection, this.loadingBuilder, this.errorBuilder, @@ -133,8 +133,7 @@ class ListenerGameWidget extends StatefulWidget { this.autofocus = true, this.mouseCursor, this.addRepaintBoundary = true, - }) : gameFactory = null, - super(key: key) { + }) : gameFactory = null { _initializeGame(game!); } @@ -198,11 +197,12 @@ class ListenerGameWidgetState /// /// This is needed because our build function invokes user code, which in turn /// may change some of the [Game]'s properties which would require the - /// [ListenerGameWidget] to be rebuilt. However, Flutter doesn't allow widgets to be + /// [ListenerGameWidget] to be rebuilt. However, Flutter doesn't allow widgets + /// to be /// marked dirty while they are building. So, this method is needed to avoid /// such a limitation and ensure that the user code can set [Game]'s - /// properties freely, and that they will be propagated to the [ListenerGameWidget] - /// at the earliest opportunity. + /// properties freely, and that they will be propagated to the + /// [ListenerGameWidget] at the earliest opportunity. Widget _protectedBuild(Widget Function() build) { late final Widget result; try { @@ -382,9 +382,10 @@ class ListenerGameWidgetState Container(); } currentGame.onGameResize(size); - // This should only be called if the game has already been - // loaded (in the case of resizing for example), since - // update otherwise should be called after onMount. + // This should only be called if the game has already + // been loaded (in the case of resizing for example), + // since update otherwise should be called after + // onMount. if (!currentGame.paused && currentGame.isAttached) { currentGame.update(0); } diff --git a/lib/behavior/behavior_manager.dart b/lib/behavior/behavior_manager.dart index 9c4973dea..86fc633f3 100644 --- a/lib/behavior/behavior_manager.dart +++ b/lib/behavior/behavior_manager.dart @@ -23,7 +23,7 @@ class BehaviorManager extends Component with BonfireHasGameRef { @override void onMount() { - _comp = parent as GameComponent; + _comp = parent! as GameComponent; super.onMount(); } } diff --git a/lib/behavior/behaviors/b_contition/b_condition.dart b/lib/behavior/behaviors/b_contition/b_condition.dart index 59dbf4905..b06a2f44f 100644 --- a/lib/behavior/behaviors/b_contition/b_condition.dart +++ b/lib/behavior/behaviors/b_contition/b_condition.dart @@ -9,9 +9,9 @@ class BCondition extends Behavior { final Behavior? doElseBehavior; BCondition({ - dynamic id, required this.condition, required this.doBehavior, + dynamic id, this.doElseBehavior, }) : super(id); diff --git a/lib/behavior/behaviors/b_contition/conditions/c_can_see.dart b/lib/behavior/behaviors/b_contition/conditions/c_can_see.dart index 31dddfc7d..75aec5926 100644 --- a/lib/behavior/behaviors/b_contition/conditions/c_can_see.dart +++ b/lib/behavior/behaviors/b_contition/conditions/c_can_see.dart @@ -18,7 +18,7 @@ class CCanSee extends Condition { @override bool execute(GameComponent comp, BonfireGameInterface game) { if (comp is Vision) { - bool see = false; + var see = false; comp.seeComponent( target, radiusVision: radiusVision, @@ -26,7 +26,7 @@ class CCanSee extends Condition { angle: angle, observed: (c) { observed?.call(c); - return see = true; + see = true; }, ); return see; diff --git a/lib/behavior/behaviors/b_contition/conditions/c_can_see_type.dart b/lib/behavior/behaviors/b_contition/conditions/c_can_see_type.dart index f3195550f..cf34e148c 100644 --- a/lib/behavior/behaviors/b_contition/conditions/c_can_see_type.dart +++ b/lib/behavior/behaviors/b_contition/conditions/c_can_see_type.dart @@ -16,14 +16,14 @@ class CCanSeeType extends Condition { @override bool execute(GameComponent comp, BonfireGameInterface game) { if (comp is Vision) { - bool see = false; + var see = false; comp.seeComponentType( radiusVision: radiusVision, visionAngle: visionAngle, angle: angle, observed: (c) { observed?.call(c); - return see = true; + see = true; }, ); return see; diff --git a/lib/behavior/behaviors/b_custom.dart b/lib/behavior/behaviors/b_custom.dart index 7bcd22263..c6291c45b 100644 --- a/lib/behavior/behaviors/b_custom.dart +++ b/lib/behavior/behaviors/b_custom.dart @@ -3,10 +3,16 @@ import 'package:bonfire/base/game_component.dart'; import 'package:bonfire/behavior/behavior.dart'; class BCustom extends Behavior { - final bool Function(double dt, GameComponent comp, BonfireGameInterface game) - behavior; + final bool Function( + double dt, + GameComponent comp, + BonfireGameInterface game, + ) behavior; - BCustom({dynamic id, required this.behavior}) : super(id); + BCustom({ + required this.behavior, + dynamic id, + }) : super(id); @override bool runAction(double dt, GameComponent comp, BonfireGameInterface game) { return behavior(dt, comp, game); diff --git a/lib/behavior/behaviors/b_move_to_component.dart b/lib/behavior/behaviors/b_move_to_component.dart index a4845af41..21e62b98b 100644 --- a/lib/behavior/behaviors/b_move_to_component.dart +++ b/lib/behavior/behaviors/b_move_to_component.dart @@ -7,8 +7,8 @@ class BMoveToComponent extends Behavior { final MovementAxis movementAxis; BMoveToComponent({ - dynamic id, required this.target, + dynamic id, this.margin = 0, this.movementAxis = MovementAxis.all, }) : super(id); diff --git a/lib/bonfire.dart b/lib/bonfire.dart index 30a55b799..0ad42f680 100644 --- a/lib/bonfire.dart +++ b/lib/bonfire.dart @@ -35,7 +35,6 @@ export 'package:bonfire/map/tiled/world_map_by_tiled.dart'; export 'package:bonfire/map/util/world_map_reader.dart'; export 'package:bonfire/map/world_map.dart'; export 'package:bonfire/mixins/attackable.dart'; -export 'package:bonfire/mixins/random_movement.dart'; export 'package:bonfire/mixins/elastic_collision.dart'; export 'package:bonfire/mixins/flip_render.dart'; export 'package:bonfire/mixins/follower.dart'; @@ -47,12 +46,13 @@ export 'package:bonfire/mixins/movement.dart'; export 'package:bonfire/mixins/movement_by_joystick.dart'; export 'package:bonfire/mixins/path_finding.dart'; export 'package:bonfire/mixins/pushable.dart'; +export 'package:bonfire/mixins/random_movement.dart'; export 'package:bonfire/mixins/sensor.dart'; +export 'package:bonfire/mixins/shader/use_shader.dart'; export 'package:bonfire/mixins/tile_recognizer.dart'; export 'package:bonfire/mixins/update_camera_by_pinch_gesture.dart'; export 'package:bonfire/mixins/use_assets_loader.dart'; export 'package:bonfire/mixins/use_barlife.dart'; -export 'package:bonfire/mixins/shader/use_shader.dart'; export 'package:bonfire/mixins/use_sprite.dart'; export 'package:bonfire/mixins/use_sprite_animation.dart'; export 'package:bonfire/mixins/vision.dart'; diff --git a/lib/camera/bonfire_camera.dart b/lib/camera/bonfire_camera.dart index fe9ba21d9..63905f1c9 100644 --- a/lib/camera/bonfire_camera.dart +++ b/lib/camera/bonfire_camera.dart @@ -42,6 +42,7 @@ class BonfireCamera extends CameraComponent with BonfireHasGameRef { return cameraRectWithSpacing.overlaps(component.toAbsoluteRect()); } + // ignore: use_setters_to_change_properties void updateSpacingVisibleMap(double space) { _spacingMap = space; } diff --git a/lib/camera/camera_effects.dart b/lib/camera/camera_effects.dart index 01a72a73a..887e5bb9a 100644 --- a/lib/camera/camera_effects.dart +++ b/lib/camera/camera_effects.dart @@ -29,7 +29,9 @@ class MyFollowBehavior extends FollowBehavior { delta = _moveVertical(delta); } - if (delta.isZero()) return; + if (delta.isZero()) { + return; + } if (delta.length <= maxSpeed * dt) { owner.position = delta..add(owner.position); } else { @@ -68,7 +70,7 @@ class MyFollowBehavior extends FollowBehavior { class ShakeEffect extends Component { final double intensity; final Duration duration; - PositionProvider get target => parent as PositionProvider; + PositionProvider get target => parent! as PositionProvider; final void Function()? onComplete; double _shakeTimer = 0.0; late Vector2 initialPosition; diff --git a/lib/collision/block_movement_collision.dart b/lib/collision/block_movement_collision.dart index 6037e6a87..10d79a0a5 100644 --- a/lib/collision/block_movement_collision.dart +++ b/lib/collision/block_movement_collision.dart @@ -21,7 +21,7 @@ mixin BlockMovementCollision on Movement { bool get blockMovementCollisionEnabled => _blockMovementCollisionEnabled; final Map _collisionsResolution = {}; CollisionData? _lastCollisionData; - CollisionData? get lastCollisionData => _lastCollisionData!; + CollisionData? get lastCollisionData => _lastCollisionData; void setupBlockMovementCollision({bool? enabled, BodyType? bodyType}) { _bodyType = bodyType ?? _bodyType; @@ -50,14 +50,14 @@ mixin BlockMovementCollision on Movement { if (_bodyType.isDynamic) { Vector2 correction; - double depth = collisionData.depth.abs(); + var depth = collisionData.depth.abs(); if (depth > 0) { depth += 0.08; } - correction = (-collisionData.normal * depth); + correction = -collisionData.normal * depth; if ((other is BlockMovementCollision) && other._bodyType.isDynamic) { - correction = (-collisionData.normal * depth / 2); + correction = -collisionData.normal * depth / 2; } correctPositionFromCollision(position + correction); @@ -82,8 +82,8 @@ mixin BlockMovementCollision on Movement { super.onCollision(intersectionPoints, other); return; } - bool stopOtherMovement = true; - bool stopMovement = other is GameComponent + var stopOtherMovement = true; + final stopMovement = other is GameComponent ? onBlockMovement(intersectionPoints, other) : true; if (other is BlockMovementCollision) { @@ -108,11 +108,11 @@ mixin BlockMovementCollision on Movement { return; } - ShapeHitbox? shape1 = _getCollisionShapeHitbox( + final shape1 = _getCollisionShapeHitbox( shapeHitboxes, intersectionPoints, ); - ShapeHitbox? shape2 = _getCollisionShapeHitbox( + final shape2 = _getCollisionShapeHitbox( other.children.query(), intersectionPoints, ); @@ -167,13 +167,13 @@ mixin BlockMovementCollision on Movement { ShapeHitbox shapeB, PositionComponent other, ) { - Vector2 normal = Vector2.zero(); - double depth = double.maxFinite; + var normal = Vector2.zero(); + var depth = double.maxFinite; - List verticesA = CollisionUtil.getPolygonVertices(shapeA); - List verticesB = CollisionUtil.getPolygonVertices(shapeB); + final verticesA = CollisionUtil.getPolygonVertices(shapeA); + final verticesB = CollisionUtil.getPolygonVertices(shapeB); - var normalAndDepthA = CollisionUtil.getNormalAndDepth( + final normalAndDepthA = CollisionUtil.getNormalAndDepth( verticesA, verticesB, ); @@ -182,7 +182,7 @@ mixin BlockMovementCollision on Movement { depth = normalAndDepthA.depth; normal = normalAndDepthA.normal; } - var normalAndDepthB = CollisionUtil.getNormalAndDepth( + final normalAndDepthB = CollisionUtil.getNormalAndDepth( verticesB, verticesA, insverted: true, @@ -193,7 +193,7 @@ mixin BlockMovementCollision on Movement { normal = normalAndDepthB.normal; } - Vector2 direction = shapeB.absoluteCenter - shapeA.absoluteCenter; + final direction = shapeB.absoluteCenter - shapeA.absoluteCenter; if (direction.dot(normal) < 0) { normal = -normal; @@ -208,18 +208,18 @@ mixin BlockMovementCollision on Movement { PositionComponent other, { bool inverted = false, }) { - Vector2 normal = Vector2.zero(); - double depth = double.maxFinite; - Vector2 axis = Vector2.zero(); + var normal = Vector2.zero(); + var depth = double.maxFinite; + var axis = Vector2.zero(); double axisDepth = 0; - List vertices = CollisionUtil.getPolygonVertices(shapeA); + final vertices = CollisionUtil.getPolygonVertices(shapeA); - for (int i = 0; i < vertices.length; i++) { - Vector2 va = vertices[i]; - Vector2 vb = vertices[(i + 1) % vertices.length]; + for (var i = 0; i < vertices.length; i++) { + final va = vertices[i]; + final vb = vertices[(i + 1) % vertices.length]; - Vector2 edge = vb - va; + final edge = vb - va; axis = Vector2(-edge.y, edge.x); axis = axis.normalized(); @@ -238,11 +238,11 @@ mixin BlockMovementCollision on Movement { } } - int cpIndex = CollisionUtil.findClosesPointOnPolygon( + final cpIndex = CollisionUtil.findClosesPointOnPolygon( shapeB.absoluteCenter, vertices, ); - Vector2 cp = vertices[cpIndex]; + final cp = vertices[cpIndex]; axis = cp - shapeB.absoluteCenter; axis = axis.normalized(); @@ -261,7 +261,7 @@ mixin BlockMovementCollision on Movement { normal = axis; } - Vector2 direction = inverted + final direction = inverted ? shapeA.absoluteCenter - shapeB.absoluteCenter : shapeB.absoluteCenter - shapeA.absoluteCenter; @@ -273,12 +273,14 @@ mixin BlockMovementCollision on Movement { } ({Vector2 normal, double depth}) _intersectCircles( - CircleHitbox shapeA, CircleHitbox shapeB) { - Vector2 normal = Vector2.zero(); - double depth = double.maxFinite; + CircleHitbox shapeA, + CircleHitbox shapeB, + ) { + var normal = Vector2.zero(); + var depth = double.maxFinite; - double distance = shapeA.absoluteCenter.distanceTo(shapeB.absoluteCenter); - double radii = shapeA.radius + shapeB.radius; + final distance = shapeA.absoluteCenter.distanceTo(shapeB.absoluteCenter); + final radii = shapeA.radius + shapeB.radius; normal = (shapeB.absoluteCenter - shapeA.absoluteCenter).normalized(); depth = radii - distance; @@ -290,13 +292,15 @@ mixin BlockMovementCollision on Movement { Iterable shapeHitboxes, Set intersectionPoints, ) { - if (shapeHitboxes.isEmpty || intersectionPoints.isEmpty) return null; + if (shapeHitboxes.isEmpty || intersectionPoints.isEmpty) { + return null; + } if (shapeHitboxes.length == 1) { return shapeHitboxes.first; } - Map distances = {}; - for (var hitbox in shapeHitboxes) { - for (var element in intersectionPoints) { + final distances = {}; + for (final hitbox in shapeHitboxes) { + for (final element in intersectionPoints) { distances[hitbox] = hitbox.absoluteCenter.distanceTo(element); if (hitbox.containsPoint(element)) { return hitbox; diff --git a/lib/geometry/circle.dart b/lib/geometry/circle.dart index c51e74932..7143fa57f 100644 --- a/lib/geometry/circle.dart +++ b/lib/geometry/circle.dart @@ -1,10 +1,9 @@ import 'dart:ui'; +import 'package:bonfire/geometry/rectangle.dart'; +import 'package:bonfire/geometry/shape.dart'; import 'package:flame/extensions.dart'; -import 'rectangle.dart'; -import 'shape.dart'; - class CircleShape extends Shape { final double radius; final RectangleShape rect; diff --git a/lib/mixins/attackable.dart b/lib/mixins/attackable.dart index 1fd4d2ea5..7ff16127c 100644 --- a/lib/mixins/attackable.dart +++ b/lib/mixins/attackable.dart @@ -33,7 +33,7 @@ mixin Attackable on GameComponent { /// Increase life void addLife(double life) { - double newLife = _life + life; + var newLife = _life + life; if (newLife > maxLife) { newLife = maxLife; @@ -54,7 +54,7 @@ mixin Attackable on GameComponent { /// reduce life void removeLife(double life) { - double newLife = _life - life; + var newLife = _life - life; if (newLife < 0) { newLife = 0; } @@ -101,9 +101,12 @@ mixin Attackable on GameComponent { removeLife(damage); } - /// This method is used to check if this component can receive damage from any attacker. + /// This method is used to check if this component can + /// receive damage from any attacker. bool checkCanReceiveDamage(AttackOriginEnum attacker) { - if (isDead || isRemoving) return false; + if (isDead || isRemoving) { + return false; + } switch (receivesAttackFrom) { case AcceptableAttackOriginEnum.ALL: return true; diff --git a/lib/mixins/elastic_collision.dart b/lib/mixins/elastic_collision.dart index 002d81615..f6d14424a 100644 --- a/lib/mixins/elastic_collision.dart +++ b/lib/mixins/elastic_collision.dart @@ -23,26 +23,26 @@ mixin ElasticCollision on BlockMovementCollision { CollisionData data, ) { if (_bouncingObjectEnabled) { - Vector2 otherVelocity = + final otherVelocity = (other is Movement) ? other.velocity : Vector2.zero(); - Vector2 relativeVelocity = otherVelocity - velocity; + final relativeVelocity = otherVelocity - velocity; if (relativeVelocity.dot(data.normal) > 0) { return super.getVelocityReflection(other, data); } - double bRestitution = + final bRestitution = (other is ElasticCollision) ? other._restitution : _restitution; - double e = min(_restitution, bRestitution); + final double e = min(_restitution, bRestitution); - double j = -(1 + e) * relativeVelocity.dot(data.normal); + var j = -(1 + e) * relativeVelocity.dot(data.normal); - double mass = (this is HandleForces) ? (this as HandleForces).mass : 1; - double massB = (other is HandleForces) ? (other).mass : 1; + final mass = (this is HandleForces) ? (this as HandleForces).mass : 1; + final massB = (other is HandleForces) ? other.mass : 1; j /= mass + massB; - Vector2 impulse = data.normal * j; + final impulse = data.normal * j; return impulse; } return super.getVelocityReflection(other, data); diff --git a/lib/mixins/flip_render.dart b/lib/mixins/flip_render.dart index a9a5bd23e..95aeb8df6 100644 --- a/lib/mixins/flip_render.dart +++ b/lib/mixins/flip_render.dart @@ -18,7 +18,7 @@ mixin FlipRender on GameComponent { bool get _needFlip => flipRenderVertically || flipRenderHorizonally; void _doFlip(Canvas canvas) { - Vector2 center = (size / 2); + final center = size / 2; canvas.save(); canvas.translate(center.x, center.y); canvas.scale( diff --git a/lib/mixins/interval_checker.dart b/lib/mixins/interval_checker.dart index db0523f66..736401823 100644 --- a/lib/mixins/interval_checker.dart +++ b/lib/mixins/interval_checker.dart @@ -12,7 +12,8 @@ import 'package:bonfire/bonfire.dart'; /// Rafaelbarbosatec /// on 17/05/22 mixin InternalChecker on Component { - /// Map available to store times that can be used to control the frequency of any action. + /// Map available to store times that can be used to control + /// the frequency of any action. Map? _timers; /// Returns true if for each time the defined millisecond interval passes. diff --git a/lib/mixins/jumper.dart b/lib/mixins/jumper.dart index c2c903b39..e513156c7 100644 --- a/lib/mixins/jumper.dart +++ b/lib/mixins/jumper.dart @@ -1,3 +1,5 @@ +// ignore_for_file: use_setters_to_change_properties + import 'package:bonfire/bonfire.dart'; import 'package:bonfire/util/collision_game_component.dart'; @@ -57,7 +59,9 @@ mixin Jumper on Movement, BlockMovementCollision { @override void onCollisionStart( - Set intersectionPoints, PositionComponent other) { + Set intersectionPoints, + PositionComponent other, + ) { if (other is CollisionMapComponent || other is TileWithCollision) { ++_tileCollisionCount; resetInterval(_tileCollisionCountKey); @@ -68,15 +72,21 @@ mixin Jumper on Movement, BlockMovementCollision { @override void onCollisionEnd(PositionComponent other) { if (other is CollisionMapComponent || other is TileWithCollision) { - if (--_tileCollisionCount == 0) resetInterval(_tileCollisionCountKey); + if (--_tileCollisionCount == 0) { + resetInterval(_tileCollisionCountKey); + } } super.onCollisionEnd(other); } @override void update(double dt) { - if (checkInterval(_tileCollisionCountKey, 100, dt, - firstCheckIsTrue: false) && + if (checkInterval( + _tileCollisionCountKey, + 100, + dt, + firstCheckIsTrue: false, + ) && !isJumping && _tileCollisionCount == 0 && displacement.y.abs() > 0.2) { diff --git a/lib/mixins/move_per_cell.dart b/lib/mixins/move_per_cell.dart index 3c706583d..179f6357c 100644 --- a/lib/mixins/move_per_cell.dart +++ b/lib/mixins/move_per_cell.dart @@ -29,7 +29,9 @@ mixin MovePerCell on Movement { @override void moveLeft({double? speed}) { if (_perCellEnabled) { - if (_perCellMoving) return; + if (_perCellMoving) { + return; + } _perCellMoving = true; add( MoveEffect.by( @@ -49,7 +51,9 @@ mixin MovePerCell on Movement { @override void moveRight({double? speed}) { if (_perCellEnabled) { - if (_perCellMoving) return; + if (_perCellMoving) { + return; + } _perCellMoving = true; add( MoveEffect.by( @@ -69,7 +73,9 @@ mixin MovePerCell on Movement { @override void moveDown({double? speed}) { if (_perCellEnabled) { - if (_perCellMoving) return; + if (_perCellMoving) { + return; + } _perCellMoving = true; add( MoveEffect.by( @@ -89,7 +95,9 @@ mixin MovePerCell on Movement { @override void moveUp({double? speed}) { if (_perCellEnabled) { - if (_perCellMoving) return; + if (_perCellMoving) { + return; + } _perCellMoving = true; add( MoveEffect.by( diff --git a/lib/mixins/movement.dart b/lib/mixins/movement.dart index 79cce457d..48e07e472 100644 --- a/lib/mixins/movement.dart +++ b/lib/mixins/movement.dart @@ -57,6 +57,7 @@ mixin Movement on GameComponent { } } + // ignore: use_setters_to_change_properties void correctPositionFromCollision(Vector2 position) { super.position = position; } @@ -185,7 +186,9 @@ mixin Movement on GameComponent { } void stopMove({bool forceIdle = false, bool isX = true, bool isY = true}) { - if (isIdle && !forceIdle) return; + if (isIdle && !forceIdle) { + return; + } setZeroVelocity(isX: isX, isY: isY); idle(); } @@ -292,8 +295,8 @@ mixin Movement on GameComponent { return; } - var normal = velocity.normalized()..absolute(); - double baseDiagonal = 0.2; + final normal = velocity.normalized()..absolute(); + const baseDiagonal = 0.2; if (velocity.x > 0 && velocity.y > 0) { if (normal.x > baseDiagonal && normal.y > baseDiagonal) { @@ -361,15 +364,15 @@ mixin Movement on GameComponent { double? speed, bool useCenter = true, }) { - double diagonalSpeed = (speed ?? this.speed) * diaginalReduction; - double dtSpeed = (speed ?? this.speed) * dtUpdate * 1.1; - double dtDiagonalSpeed = diagonalSpeed * dtUpdate * 1.1; + final diagonalSpeed = (speed ?? this.speed) * diaginalReduction; + final dtSpeed = (speed ?? this.speed) * dtUpdate * 1.1; + final dtDiagonalSpeed = diagonalSpeed * dtUpdate * 1.1; final rect = rectCollision; final compCenter = rect.centerVector2; final compPosition = rect.positionVector2; - double diffX = position.x - (useCenter ? compCenter : compPosition).x; - double diffY = position.y - (useCenter ? compCenter : compPosition).y; + final diffX = position.x - (useCenter ? compCenter : compPosition).x; + final diffY = position.y - (useCenter ? compCenter : compPosition).y; if (diffX.abs() < dtSpeed && diffY.abs() < dtSpeed) { return false; @@ -444,7 +447,7 @@ mixin Movement on GameComponent { double? displacement, Iterable? ignoreHitboxes, }) { - double maxDistance = displacement ?? (speed * (dtUpdate * 2)); + final maxDistance = displacement ?? (speed * (dtUpdate * 2)); switch (direction) { case Direction.right: @@ -529,26 +532,26 @@ mixin Movement on GameComponent { double maxDistance, { Iterable? ignoreHitboxes, }) { - double distance = maxDistance; + var distance = maxDistance; final centerComp = rectCollision.center.toVector2(); - Vector2 origin1 = centerComp; - Vector2 origin3 = centerComp; + var origin1 = centerComp; + var origin3 = centerComp; final size = rectCollision.sizeVector2; final vetorDirection = direction.toVector2(); switch (direction) { case Direction.right: case Direction.left: - double halfY = (size.y / 2); - double halfX = (size.y / 2); + final halfY = size.y / 2; + final halfX = size.y / 2; origin1 = origin1.translated(0, -halfY); origin3 = origin3.translated(0, halfY); distance += halfX; break; case Direction.up: case Direction.down: - double halfX = (size.x / 2); - double halfY = (size.y / 2); + final halfX = size.x / 2; + final halfY = size.y / 2; origin1 = origin1.translated(-halfX, 0); origin3 = origin3.translated(halfX, 0); distance += halfY; @@ -558,20 +561,20 @@ mixin Movement on GameComponent { case Direction.downLeft: case Direction.downRight: } - bool check1 = raycast( + final check1 = raycast( vetorDirection, maxDistance: distance, origin: origin1, ignoreHitboxes: ignoreHitboxes, ) != null; - bool check2 = raycast( + final check2 = raycast( vetorDirection, maxDistance: distance, ignoreHitboxes: ignoreHitboxes, ) != null; - bool check3 = raycast( + final check3 = raycast( vetorDirection, maxDistance: distance, origin: origin3, diff --git a/lib/mixins/movement_by_joystick.dart b/lib/mixins/movement_by_joystick.dart index fb893db54..4604f2a30 100644 --- a/lib/mixins/movement_by_joystick.dart +++ b/lib/mixins/movement_by_joystick.dart @@ -3,7 +3,8 @@ import 'package:bonfire/bonfire.dart'; enum MovementByJoystickType { direction, angle } class MovementByJoystickProps { - /// MovementByJoystickType.direction if you only want the 8 directions movement. + /// MovementByJoystickType.direction if you only want the + /// 8 directions movement. /// Set MovementByJoystickType.angle to have full 360 movement MovementByJoystickType moveType; bool intensityEnabled; diff --git a/lib/mixins/pointer_detector.dart b/lib/mixins/pointer_detector.dart index 3d715eada..737857dc3 100644 --- a/lib/mixins/pointer_detector.dart +++ b/lib/mixins/pointer_detector.dart @@ -13,7 +13,7 @@ mixin PointerDetector { mixin PointerDetectorHandler on Component { // If return 'true' this event is not relay to others components. bool handlerPointerDown(PointerDownEvent event) { - for (var child in children) { + for (final child in children) { if (child is GameComponent) { if (child.handlerPointerDown(event)) { return true; @@ -25,7 +25,7 @@ mixin PointerDetectorHandler on Component { // If return 'true' this event is not relay to others components. bool handlerPointerMove(PointerMoveEvent event) { - for (var child in children) { + for (final child in children) { if (child is GameComponent) { if (child.handlerPointerMove(event)) { return true; @@ -37,7 +37,7 @@ mixin PointerDetectorHandler on Component { // If return 'true' this event is not relay to others components. bool handlerPointerUp(PointerUpEvent event) { - for (var child in children) { + for (final child in children) { if (child is GameComponent) { if (child.handlerPointerUp(event)) { return true; @@ -49,7 +49,7 @@ mixin PointerDetectorHandler on Component { // If return 'true' this event is not relay to others components. bool handlerPointerCancel(PointerCancelEvent event) { - for (var child in children) { + for (final child in children) { if (child is GameComponent) { if (child.handlerPointerCancel(event)) { return true; diff --git a/lib/mixins/pushable.dart b/lib/mixins/pushable.dart index d51e7c99b..96f7d0578 100644 --- a/lib/mixins/pushable.dart +++ b/lib/mixins/pushable.dart @@ -56,10 +56,10 @@ mixin Pushable on Movement { } case PushableFromEnum.ALL: } - GameComponent component = other; + final component = other; if (component is Movement && onPush(component)) { - Vector2 displacement = (rectCollision.centerVector2 - - component.rectCollision.centerVector2); + final displacement = rectCollision.centerVector2 - + component.rectCollision.centerVector2; if (_pushPerCellEnabled) { _movePercell(component, displacement); } else { @@ -111,7 +111,7 @@ mixin Pushable on Movement { if (_percellMoving) { return; } - Vector2 cellSize = _cellSize ?? size; + final cellSize = _cellSize ?? size; _percellMoving = true; if (displacement.x.abs() > displacement.y.abs()) { if (displacement.x < 0) { diff --git a/lib/mixins/random_movement.dart b/lib/mixins/random_movement.dart index bd0657bb9..df4cdf23a 100644 --- a/lib/mixins/random_movement.dart +++ b/lib/mixins/random_movement.dart @@ -32,7 +32,8 @@ class RandomMovementDirections { ); } -/// Mixin responsible for adding random movement like enemy walking through the scene +/// Mixin responsible for adding random movement like enemy +/// walking through the scene mixin RandomMovement on Movement { // ignore: constant_identifier_names static const _KEY_INTERVAL_KEEP_STOPPED = 'INTERVAL_RANDOM_MOVEMENT'; @@ -105,7 +106,7 @@ mixin RandomMovement on Movement { void correctPositionFromCollision(Vector2 position) { super.correctPositionFromCollision(position); if (this is Jumper) { - if ((this is BlockMovementCollision)) { + if (this is BlockMovementCollision) { final isV = (this as BlockMovementCollision) .lastCollisionData ?.direction @@ -157,12 +158,12 @@ mixin RandomMovement on Movement { bool checkDirectionWithRayCast, RandomMovementDirections directions, ) { - int index = 0; + var index = 0; while (index < 100) { final distance = _getDistance(minDistance, maxDistance); final direction = _getDirection(directions); final targetPosition = _getTargetPosition(direction, distance); - bool isRaycastOk = true; + var isRaycastOk = true; if (checkDirectionWithRayCast) { isRaycastOk = canMove( @@ -201,8 +202,9 @@ class _RandomPositionTarget { final Direction direction; final double distance; - _RandomPositionTarget( - {required this.position, - required this.direction, - required this.distance}); + _RandomPositionTarget({ + required this.position, + required this.direction, + required this.distance, + }); } diff --git a/lib/mixins/sensor.dart b/lib/mixins/sensor.dart index c517628ff..0f37a82b5 100644 --- a/lib/mixins/sensor.dart +++ b/lib/mixins/sensor.dart @@ -1,11 +1,12 @@ import 'dart:async'; import 'package:bonfire/bonfire.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; /// Mixin responsible for adding trigger to detect other objects above /// T is a type that Sensor will be find contact. mixin Sensor on GameComponent { - static Color color = const Color(0xFFF44336).withOpacity(0.5); + static Color color = const Color(0xFFF44336).setOpacity(0.5); static const _sensorIntervalKey = 'SensorContact'; int _intervalCallback = 100; bool sensorEnabled = true; @@ -13,14 +14,14 @@ mixin Sensor on GameComponent { void onContact(T component) {} void onContactExit(T component) {} - void setSensorInterval(int intervalCallback) { + set sensorInterval(int intervalCallback) { _intervalCallback = intervalCallback; } @override Future onLoad() async { await super.onLoad(); - bool containsShape = children.query().isNotEmpty; + final containsShape = children.query().isNotEmpty; if (!containsShape) { add(RectangleHitbox(size: size, isSolid: true)); } diff --git a/lib/mixins/shader/shader_setter.dart b/lib/mixins/shader/shader_setter.dart index 582bb7780..5bf005f19 100644 --- a/lib/mixins/shader/shader_setter.dart +++ b/lib/mixins/shader/shader_setter.dart @@ -43,7 +43,7 @@ class ShaderSetter { void apply(FragmentShader shader) { _indexFloat = startFloatIndex; _indexImage = startImageIndex; - for (var item in values) { + for (final item in values) { if (item is SetterDouble) { _setFloat(shader, item.value); } @@ -58,10 +58,10 @@ class ShaderSetter { if (item is SetterColor) { final color = item.value; - _setFloat(shader, color.red / 255 * color.opacity); - _setFloat(shader, color.green / 255 * color.opacity); - _setFloat(shader, color.blue / 255 * color.opacity); - _setFloat(shader, color.opacity); + _setFloat(shader, color.r * color.a); + _setFloat(shader, color.g * color.a); + _setFloat(shader, color.b * color.a); + _setFloat(shader, color.a); } } } diff --git a/lib/mixins/shader/shader_util.dart b/lib/mixins/shader/shader_util.dart index f8d1a1320..59987e614 100644 --- a/lib/mixins/shader/shader_util.dart +++ b/lib/mixins/shader/shader_util.dart @@ -14,9 +14,9 @@ abstract class ShaderUtils { ui.Image? snapshot, }) { { - ui.Image? innerSnapshot = snapshot; - ui.PictureRecorder recorder = ui.PictureRecorder(); - ui.Canvas canvasRecorder = ui.Canvas(recorder); + var innerSnapshot = snapshot; + final recorder = ui.PictureRecorder(); + final canvasRecorder = ui.Canvas(recorder); canvasRecorder.scale(shaderCanvasScale); record(canvasRecorder); diff --git a/lib/mixins/shader/use_shader.dart b/lib/mixins/shader/use_shader.dart index e9494b7dc..bc4074016 100644 --- a/lib/mixins/shader/use_shader.dart +++ b/lib/mixins/shader/use_shader.dart @@ -1,8 +1,7 @@ import 'dart:ui' as ui; import 'package:bonfire/bonfire.dart'; - -import 'shader_util.dart'; +import 'package:bonfire/mixins/shader/shader_util.dart'; export 'shader_setter.dart'; @@ -45,7 +44,7 @@ mixin UseShader on PositionComponent { decoratorCanvas, (recorderCanvas) { render(recorderCanvas); - for (var c in children) { + for (final c in children) { c.renderTree(recorderCanvas); } }, diff --git a/lib/mixins/tile_recognizer.dart b/lib/mixins/tile_recognizer.dart index 4c37b9cb8..59dbfc532 100644 --- a/lib/mixins/tile_recognizer.dart +++ b/lib/mixins/tile_recognizer.dart @@ -26,7 +26,9 @@ mixin TileRecognizer on GameComponent { /// Method that checks what types map tile is currently List tileTypeListBelow() { - if (!hasGameRef) return []; + if (!hasGameRef) { + return []; + } final map = gameRef.map; if (map.getRenderedTiles().isNotEmpty) { return tileListBelow().map((e) => e.tileClass!).toList(); @@ -62,8 +64,7 @@ mixin TileRecognizer on GameComponent { final map = gameRef.map; if (map.layers.isNotEmpty) { return map.getRenderedTiles().where((element) { - return (element.overlaps(rectCollision) && - (element.properties != null)); + return element.overlaps(rectCollision) && (element.properties != null); }); } return []; diff --git a/lib/mixins/update_camera_by_pinch_gesture.dart b/lib/mixins/update_camera_by_pinch_gesture.dart index 0340f6a9f..13dc652c9 100644 --- a/lib/mixins/update_camera_by_pinch_gesture.dart +++ b/lib/mixins/update_camera_by_pinch_gesture.dart @@ -1,6 +1,7 @@ import 'package:bonfire/bonfire.dart'; -// Mixin usend in component that use PinchGesture to update zoom and cameraposition in pich gestures. +// Mixin usend in component that use PinchGesture to update zoom and +//cameraposition in pich gestures. mixin UpdateCameraByPinchGesture on PinchGesture { double _initialZoom = 1.0; Vector2 _initialPosition = Vector2.zero(); @@ -20,8 +21,7 @@ mixin UpdateCameraByPinchGesture on PinchGesture { final scale = event.factorDistance; gameRef.camera.zoom = _initialZoom * scale; final diff = event.diffCenter; - gameRef.camera.position = - (_initialPosition - diff / (gameRef.camera.zoom)); + gameRef.camera.position = _initialPosition - diff / (gameRef.camera.zoom); } super.onPinchUpdate(event); diff --git a/lib/mixins/vision.dart b/lib/mixins/vision.dart index eb129ed55..ced038e95 100644 --- a/lib/mixins/vision.dart +++ b/lib/mixins/vision.dart @@ -3,13 +3,14 @@ import 'dart:math'; import 'package:bonfire/bonfire.dart'; import 'package:bonfire/geometry/polygon.dart'; import 'package:bonfire/geometry/rectangle.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; import 'package:flutter/material.dart'; /// Mixin used to adds basic Vision to the component mixin Vision on GameComponent { // ignore: constant_identifier_names static const VISION_360 = 6.28319; - final Paint _paint = Paint()..color = Colors.red.withOpacity(0.5); + final Paint _paint = Paint()..color = Colors.red.setOpacity(0.5); bool _drawVision = false; bool _checkWithRaycast = true; final Map _polygonCache = {}; @@ -22,14 +23,15 @@ mixin Vision on GameComponent { bool checkWithRaycast = true, int countPolygonPoints = 20, }) { - assert(countPolygonPoints % 2 == 0, 'countPolygonPoints must be even'); + assert(countPolygonPoints.isEven, 'countPolygonPoints must be even'); _drawVision = drawVision; _checkWithRaycast = checkWithRaycast; _countPolygonPoints = countPolygonPoints; - _paint.color = color ?? Colors.red.withOpacity(0.5); + _paint.color = color ?? Colors.red.setOpacity(0.5); } - /// This method we notify when detect the component when enter in [radiusVision] configuration + /// This method we notify when detect the component when enter + /// in [radiusVision] configuration /// Method that bo used in [update] method. /// [visionAngle] in radians /// [angle] in radians. @@ -46,7 +48,7 @@ mixin Vision on GameComponent { return _currentShape = null; } - PolygonShape shape = _getShapeVision(radiusVision, visionAngle, angle); + final shape = _getShapeVision(radiusVision, visionAngle, angle); if (_canSee(shape, component, radiusVision)) { observed(component); @@ -71,12 +73,12 @@ mixin Vision on GameComponent { position: rect.positionVector2, ); - bool inShape = shape.isCollision(otherShape); + final inShape = shape.isCollision(otherShape); if (inShape) { if (_checkWithRaycast) { - Vector2 myCenter = rectCollision.center.toVector2(); - Vector2 compCenter = component.rectCollision.center.toVector2(); - Vector2 direction = (compCenter - myCenter).normalized(); + final myCenter = rectCollision.center.toVector2(); + final compCenter = component.rectCollision.center.toVector2(); + final direction = (compCenter - myCenter).normalized(); final result = raycast( direction, @@ -84,7 +86,7 @@ mixin Vision on GameComponent { origin: myCenter, ignoreHitboxes: _getCanNotSeenHitbox(), ); - var vParent = result?.hitbox?.parent; + final vParent = result?.hitbox?.parent; return vParent == component || vParent == null; } return true; @@ -93,27 +95,28 @@ mixin Vision on GameComponent { return false; } - /// This method we notify when detect components by type when enter in [radiusVision] configuration + /// This method we notify when detect components by type when enter + /// in [radiusVision] configuration /// Method that bo used in [update] method. /// [visionAngle] in radians /// [angle] in radians. PolygonShape? seeComponentType({ - required Function(List) observed, + required void Function(List) observed, VoidCallback? notObserved, double radiusVision = 32, double? visionAngle, double angle = 3.14159, }) { - var compVisible = gameRef.visibles(); + final compVisible = gameRef.visibles(); if (compVisible.isEmpty) { notObserved?.call(); return _currentShape = null; } - PolygonShape shape = _getShapeVision(radiusVision, visionAngle, angle); + final shape = _getShapeVision(radiusVision, visionAngle, angle); - List compObserved = compVisible.where((comp) { + final compObserved = compVisible.where((comp) { return _canSee(shape, comp, radiusVision); }).toList(); @@ -131,34 +134,38 @@ mixin Vision on GameComponent { double angle, Vector2 position, ) { - double angleV = angleVision ?? VISION_360; - double nextX = radiusVision * cos(angle); - double nextY = radiusVision * sin(angle); - Offset point = Offset(nextX, nextY); - List pointsP = []; + final angleV = angleVision ?? VISION_360; + final nextX = radiusVision * cos(angle); + final nextY = radiusVision * sin(angle); + final point = Offset(nextX, nextY); + final pointsP = []; List.generate(_countPolygonPoints ~/ 2, (index) { if (index == 0) { - pointsP.add(point - .rotate(angleV / _countPolygonPoints, Offset.zero) - .toVector2()); + pointsP.add( + point.rotate(angleV / _countPolygonPoints, Offset.zero).toVector2(), + ); } else { - pointsP.add(pointsP.last - .toOffset() - .rotate(angleV / _countPolygonPoints, Offset.zero) - .toVector2()); + pointsP.add( + pointsP.last + .toOffset() + .rotate(angleV / _countPolygonPoints, Offset.zero) + .toVector2(), + ); } }); - List pointsN = []; + final pointsN = []; List.generate(_countPolygonPoints ~/ 2, (index) { if (index == 0) { - pointsN.add(point - .rotate(angleV / -_countPolygonPoints, Offset.zero) - .toVector2()); + pointsN.add( + point.rotate(angleV / -_countPolygonPoints, Offset.zero).toVector2(), + ); } else { - pointsN.add(pointsN.last - .toOffset() - .rotate(angleV / -_countPolygonPoints, Offset.zero) - .toVector2()); + pointsN.add( + pointsN.last + .toOffset() + .rotate(angleV / -_countPolygonPoints, Offset.zero) + .toVector2(), + ); } }); @@ -199,9 +206,9 @@ mixin Vision on GameComponent { double? visionAngle, double angle, ) { - String key = '$radiusVision/$visionAngle/$angle'; + final key = '$radiusVision/$visionAngle/$angle'; PolygonShape shape; - var center = rectCollision.centerVector2; + final center = rectCollision.centerVector2; if (_polygonCache.containsKey(key)) { shape = _polygonCache[key]!; shape.position = center; @@ -213,7 +220,7 @@ mixin Vision on GameComponent { } List _getCanNotSeenHitbox() { - var sensorHitBox = []; + final sensorHitBox = []; gameRef.query(onlyVisible: true).forEach((e) { sensorHitBox.addAll(e.children.query()); });