【发布时间】: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);
}
}
}
【问题讨论】: