【问题标题】:How to make an object continue moving on one axis although it's velocity is blocked on the other one如何使物体继续在一个轴上移动,尽管它的速度在另一个轴上被阻止
【发布时间】:2018-10-01 20:48:10
【问题描述】:

标题说明了一切,但举个例子只是为了让我的意思更清楚:

一个物体的速度是 x: 10, y: 10,所以它对角线向下向右移动。现在假设对象已经位于可通行区域的右边界,但其下方有足够的空间。我希望对象直接向南移动 (y:10) 并丢弃 x 轴。

但我不确定我将如何实现这一目标?

class MovementComponent
{
  constructor(subject, collisionHandler, speed)
  {
    this.subject = subject;
    this.collisionHandler = collisionHandler;
    this.speed = speed;
    this.velocity = new Vector2(0, 0);
  }

  affectVelocity(axis, positive)
  {
    var force = new Vector2();
    if (axis == "X") {
      force = (positive) ? new Vector2(this.speed, 0) : new Vector2(-this.speed, 0);
    } else if (axis == "Y") {
      force = (positive) ? new Vector2(0, this.speed) : new Vector2(0, -this.speed);
    }
    this.velocity.add(force);
  }

  update()
  {
    if (!this.velocity.isZero()) { // No reason to run collision code when the object isn't moving.
      this.subject.position.add(this.velocity);
      if (!this.collisionHandler.canObjectBeHere(this.subject)) {
        this.subject.position.subtract(this.velocity);
        this.getCloseAsPossible(0.9);
      }
    }
    this.velocity = new Vector2(0, 0); // Reset the velocity to get a full stop when no keys are down. This is instead of applying friction. 
  }

  getCloseAsPossible(velocityModifier)
  {
    this.velocity.multiply(velocityModifier);
    this.subject.position.add(this.velocity);
    if (!this.collisionHandler.canObjectBeHere(this.subject)) {
       this.subject.position.subtract(this.velocity);
       this.getCloseAsPossible(velocityModifier - 0.1);
    }
  }
}

【问题讨论】:

    标签: javascript game-physics


    【解决方案1】:

    您必须在 x 轴通过某个值后锁定它。假设您说的对象正在与屏幕右上角发生碰撞:

    如果您的屏幕尺寸为 800x600,您可能会在每次重新渲染时更新对象位置 +10 以提供运动效果。一旦你的对象到达,screenWidth - objectWidth你停止在对象的 x 轴上加 10s position. That way, since youre 不断地在 y 轴上加 10,你的对象将自动“落”在屏幕上。您可以在 y 轴达到 screenHeight - objectHeight 时停止向 y 轴添加 10,这是您的对象在离开屏幕之前应该能够到达的最大 y 轴位置。

    【讨论】:

    • 所以在我看来,我需要扩展我的碰撞逻辑,这样我才能检测到碰撞来自哪个方向,这样我就可以锁定那个轴。 ?
    • 就是这样。只是不要将其视为“方向”。屏幕上的每个对象都会有一个边界框,比如说……一个矩形。现在,假设每个角上有 4 个点的矩形,并且这些点都不能穿过其他碰撞对象(或屏幕)的边界框。这更像是“每帧位置”的问题,而不是它们来自的方向
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    相关资源
    最近更新 更多