如何在重力火焰库中将重力应用于游戏对象

问题描述 投票:1回答:1

我无法通过在body.position.y中更新Rect在我的代码中的位置来向我想沿Y轴自由下落的Rect对象施加重力。这是我的代码的片段:

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();
  }

请问我能做什么?

flutter box2d flame
1个回答
0
投票

您需要为游戏使用Flame中的Box2DGame(flame 0.22.0 ^)类,并且您要对其施加重力的对象需要扩展BodyComponent,然后创建BodyComponent的实例在Box2DGame中使用add函数将其添加到游戏循环中,以确保每次迭代都在其上调用updaterender

火焰源here中有一个很好的例子。

还请记住,如果重力为正,则物体将向上飞行。

© www.soinside.com 2019 - 2024. All rights reserved.