如何使对象继续在一个轴上移动,尽管它的速度在另一个轴上被阻止



>Title说明了一切,但一个例子只是为了更清楚地说明我的意思:

对象的速度为 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);
}
}
}

您必须在x 轴传递某个值后锁定它。假设物体正在碰撞屏幕右上角,如您所说:

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

相关内容

最新更新