我无法将重力应用于 Rect 对象,我想通过在我的代码中使用 body.position.y 更新 Rect 的位置来沿 Y 轴自由落下。这是我的代码片段:
import 'dart:ui';
import 'package:box2d_flame/box2d.dart';
import 'package:flame/sprite.dart';
import 'package:mimo/mimo-game.dart';
class Mimo {
final MimoGame game;
CircleShape shape;
Body body;
List<Sprite> mimoSprite;
List<Sprite> deadSprite;
double flyingSpriteIndex = 0;
Rect mimoRect;
bool isDead = false;
bool isOffScreen = false;
Mimo(this.game, double x, double y) {
shape = CircleShape(); //build in shape, just set the radius
shape.p.setFrom(Vector2.zero());
shape.radius = .1; //10cm ball
BodyDef bd = BodyDef();
bd.position = new Vector2(x,y);
bd.type = BodyType.DYNAMIC;
body = game.world.createBody(bd);
body.userData = this;
FixtureDef fd = FixtureDef();
fd.restitution = 0.5;
fd.density = 0.05;
fd.friction = 0;
fd.shape = shape;
body.createFixtureFromFixtureDef(fd);
mimoSprite = List();
mimoSprite.add(Sprite('mimo/mimo-1.png'));
mimoSprite.add(Sprite('mimo/mimo-2.png'));
mimoSprite.add(Sprite('mimo/mimo-3.png'));
mimoSprite.add(Sprite('mimo/mimo-4.png'));
mimoSprite.add(Sprite('mimo/mimo-5.png'));
deadSprite = List();
mimoRect = Rect.fromLTWH(body.position.x, body.position.y, game.mimoSize, game.mimoSize);
}
void render(Canvas c) {
mimoSprite[flyingSpriteIndex.toInt()].renderRect(c, mimoRect.inflate(2));
}
void update(double t) {
mimoRect = mimoRect.translate(body.position.x, body.position.y);
}
}
在update
我使用这条线的方法中mimoRect = mimoRect.translate(body.position.x, body.position.y);
,body.position 可以Rect
实时更新我的对象。但是什么都没有发生,因为我生成的对象总是固定在一个位置并且不会移动。我决定登录body.position.y
控制台并注意到它没有改变。
在我的主课中,我创建了一个这样的世界对象:
//Needed for Box2D
static const int WORLD_POOL_SIZE = 100;
static const int WORLD_POOL_CONTAINER_SIZE = 10;
//Main physic object -> our game world
World world;
//Zero vector -> no gravity
final Vector2 _gravity = Vector2(0, 4.0);
Body body;
CircleShape shape;
//Scale to get from rad/s to something in the game, I like the number 5
double sensorScale = 5;
//Draw class
Paint paint;
//Initial acceleration -> no movement as its (0,0)
Vector2 acceleration = Vector2.zero();
MimoGame() {
world = new World.withPool(_gravity,
DefaultWorldPool(WORLD_POOL_SIZE, WORLD_POOL_CONTAINER_SIZE));
initialize();
}
请知道我能做什么?