【问题标题】:Constant box2d body moving to point at a time [closed]常量box2d体一次移动到一个点[关闭]
【发布时间】:2013-10-19 21:43:26
【问题描述】:

我在 Andengine 中有 box2d 身体。我想一次将这个身体从 (0,0) 移动到 (100,100)(恒定速度)。这怎么可能?我试过这个代码: this.body.setLinearVelocity(new Vector2(1, 0));但它一直在不停地移动。

【问题讨论】:

  • 你的问题一点都不清楚。您希望它像传送一样立即移动,还是以恒定速度移动?身体不停地转动有什么问题?你想让它停止在两者之间移动吗?你有重力吗?也使用 new Vector2(1,1) 代替...
  • 我有一个身体。我希望它在 (0,0)px 和 (100,100)px 之间移动,不像传送。我希望它在 5 秒内移动(V 速度或 2V 速度) .不是传送。
  • 假设您没有任何重力并且身体的线性阻尼设置为 0 并且您的像素与米的比率为 1 一个简单的 body.setLinearVelocity(new Vector2(20, 20)) 应该可以完成这项工作。但是,如果没有关于您的场景的更多信息,没有人可以帮助您。
  • 有重力。我的意思是移动身体 A 点到 B 点。我尝试了这个 body.setLinearVelocity(new Vector2(20, 20)) 。但是当我使用这个时,身体继续移动到无限..我想让身体停在一个点上。

标签: android box2d andengine


【解决方案1】:

我想沿预定义路径移动的最简单方法是使用Body.setTransform(...)。这样我们基本上可以忽略所有的力、摩擦力、扭矩、碰撞等,直接设置身体的位置。

我不知道Andengine,所以这只是伪代码:

public void updateGameLoop(float deltaTime) {
    Vector2 current = body.getPosition();
    Vector2 target = new Vector2(100, 100);

    if (!current.equals(target)) {
        float speed = 20f;
        Vector2 direction = target.sub(current);
        float distanceToTarget = direction.len();
        float travelDistance = speed * deltaTime;

        // the target is very close, so we set the position to the target directly
        if (distanceToTarget <= travelDistance) {
            body.setTransform(target, body.getAngle());
        } else {
            direction.nor();
            // move a bit in the target direction 
            body.setTransform(current.add(direction.mul(travelDistance)), body.getAngle());
        }
    }
}

【讨论】:

  • 使用setTransform() 移动对象会导致模拟无法以最佳方式执行并可能导致错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多