我正在使用Flame在Flutter中构建2D游戏,但是我遇到了CAST问题。
import 'dart:ui';
class BarrierRect extends Rect {
BarrierRect.fromLTWH(double left, double top, double width, double height) : super.fromLTWH(left, top, width, height);
bool _barrier = true;
bool get isBarrier {
return this._barrier;
}
set isBarrier(bool isBarrier) {
this._barrier = isBarrier;
}
BarrierRect shift(Offset offset) {
Rect rect = super.shift(offset);
return rect as BarrierRect; // There is an exception in this line
}
}
以下是例外的详细信息。
I/flutter (18075): ══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (18075): The following _CastError was thrown during a scheduler callback:
I/flutter (18075): type 'Rect' is not a subtype of type 'BarrierRect' in type cast
I/flutter (18075):
I/flutter (18075): When the exception was thrown, this was the stack:
I/flutter (18075): #0 BarrierRect.shift (package:flappy_bird/util/barrier-rect.dart:19:17)
I/flutter (18075): #1 GameBorder.update (package:flappy_bird/component/game-border.dart:43:25)
I/flutter (18075): #2 FlyGame.update (package:flappy_bird/fly-game.dart:40:18)
I/flutter (18075): #3 GameRenderBox._update (package:flame/game.dart:293:10)
I/flutter (18075): #4 GameRenderBox._tick (package:flame/game.dart:286:5)
I/flutter (18075): #5 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1016:15)
I/flutter (18075): #6 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleBeginFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:934:11)
I/flutter (18075): #7 __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:367:8)
那么,我应该怎么做才能返回BarrierRect类?
答案 0 :(得分:1)
Rect.shift
不会创建新的BarrierRect
:
Rect shift(Offset offset) {
return Rect.fromLTRB(left + offset.dx, top + offset.dy, right + offset.dx, bottom + offset.dy);
}
https://api.flutter.dev/flutter/dart-ui/Rect/shift.html
所以从Rect
返回的super.shift(...)
无法转换为BarrierRect
是正确的。
请考虑将BarrierRect
修饰为给定的Rect
,或者只是简单地复制其中一个。
class BarrierRect extends Rect {
BarrierRect.fromRect(final Rect rect) : super(...);
bool _barrier = true;
bool get isBarrier {
return this._barrier;
}
set isBarrier(bool isBarrier) {
this._barrier = isBarrier;
}
BarrierRect shift(Offset offset) {
Rect rect = super.shift(offset);
return BarrierRect.fromRect(rect);
}
}
class BarrierRect {
final Rect origin;
BarrierRect(this.origin);
...
BarrierRect shift(Offset offset) {
Rect rect = origin.shift(offset);
return BarrierRect(rect);
}
}