Box2d对角线运动时的静态速度更快

问题描述:

所以我希望我的球员能够快速移动。现在我的代码看起来像Box2d对角线运动时的静态速度更快

move() { 
    var vel = this.body.GetLinearVelocity() 

    if(!this.pressingDown && !this.pressingUp){ 
     vel.y = 0; 
    } 
    if(!this.pressingRight && !this.pressingRight){ 
     vel.x = 0; 
    } 

    if(this.pressingDown){ 
     vel.y = this.speed; 
    } 
    if(this.pressingUp){ 
     vel.y = -this.speed; 

    } 
    if(this.pressingRight){ 
     vel.x = this.speed; 

    } 

    if(this.pressingLeft){ 
     vel.x = -this.speed 
    } 
    this.body.SetLinearVelocity(vel) 

这个工程,但是当我移动diagnolly时,播放器移动速度超过最大速度。我该如何解决?

确定方向单位矢量,然后乘以this.speed。这样,速度的大小总是为this.speed。否则,正如您发现的那样,您的速度可能是sqrt(this.speed * this.speed * 2),而不仅仅是this.speed

确定此方向单位矢量的一种方法是根据按下的按键识别想要移动的角度,然后获取该角度的正弦和余弦值。所以当this.pressingRight时,角度为0.当this.pressingUp时,角度为90度(或Pi/2弧度)。或者当this.pressingUp && this.pressingRight,角度是45度(Pi/4弧度)。只需填写所有可用组合的if语句即可。也许把它放在自己的函数中,叫做getAngleInRadiansForKeyPresses。然后

执行(以伪的JavaScript代码)可能看起来像:

move() { 
    var angle = getAngleInRadiansForKeyPresses(); 
    var vel = new b2Vec2(Math.cos(angle) * this.speed, Math.sin(angle) * this.speed); 
    this.body.SetLinearVelocity(vel); 
}