在波纹管代码中"angle %= 2 * math.pi;"的目的是什么?



我正在从 Flame 引擎源运行此示例,我想知道在更新方法中angle %= 2 * math.pi;的目的是什么。评论它也不影响矩形的圆形动画!如果有数学原因,请尽可能提供相关文章的链接。

import 'dart:math' as math;
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame/palette.dart';
import 'package:flutter/material.dart';
void main() {
runApp(
GameWidget(
game: MyGame(),
),
);
}
/// This example simply adds a rotating white square on the screen, if you press
/// somewhere other than on the existing square another square will be added and
/// if you press on a square it will be removed.
class MyGame extends FlameGame with DoubleTapDetector, HasTappables {
bool running = true;
@override
Future<void> onLoad() async {
add(Square(Vector2(100, 200)));
}
@override
void onTapUp(int id, TapUpInfo info) {
super.onTapUp(id, info);
if (!info.handled) {
final touchPoint = info.eventPosition.game;
add(Square(touchPoint));
}
}
@override
void onDoubleTap() {
if (running) {
pauseEngine();
} else {
resumeEngine();
}
running = !running;
}
}
class Square extends PositionComponent with Tappable {
static const speed = 0.25;
static const squareSize = 128.0;
static Paint white = BasicPalette.white.paint();
static Paint red = BasicPalette.red.paint();
static Paint blue = BasicPalette.blue.paint();
Square(Vector2 position) : super(position: position);
@override
Future<void> onLoad() async {
super.onLoad();
size.setValues(squareSize, squareSize);
anchor = Anchor.center;
}
@override
void render(Canvas canvas) {
canvas.drawRect(size.toRect(), white);
canvas.drawRect(const Rect.fromLTWH(0, 0, 30, 30), red);
canvas.drawRect(Rect.fromLTWH(width / 2, height / 2, 3, 3), blue);
}
@override
void update(double dt) {
super.update(dt);
angle += speed * dt;
angle %= 2 * math.pi;      //<---- What is the reason behind this line?
}
@override
bool onTapUp(TapUpInfo info) {
removeFromParent();
return true;
}
}

在某些时候,如果你没有很高的转速,很长一段时间后,角度会溢出double可以容纳的角度。

这里的角度以弧度为单位,一个完整的圆是 2π (360°)。 由于当我们旋转了一个完整的圆时,我们也可以再次回到 0,我们使用模来删除当前处于angle中的所有"未使用"的完整圆 .

如果超过 2*pi 会发生什么。

什么都不会发生,它只会继续旋转,但角度会继续增长到不必要的大值。

它确保angle永远不会超过 2×PI,即以弧度为单位的角度的最大值。通过执行此值的模数,任何超过 2×PI 的数字都将从 0 开始环绕。

最新更新