【问题标题】:Changing direction while moving移动时改变方向
【发布时间】:2016-04-06 20:58:34
【问题描述】:

我正在制作一个宇宙飞船的游戏,当按下左右键时它会旋转,当按下向上键时会向前移动。

目前这艘船可以在前进的同时旋转,但它会继续朝着它前进的方向前进。

我将如何做到这一点,以便在按住向上键时飞船可以改变其移动方向?

这是 SpaceShip 类的更新方法:

public void update(){
    radians += ri;
    System.out.println(radians);
    if(radians < 0){
        radians = 2 * Math.PI;
    }if(radians > (2 * Math.PI)){
        radians = 0;
    }

    x += xx;
    y += yy;
}

这是正确的事件:

    public void actionPerformed(ActionEvent e) {
    if(pressed){
        Board.getShip().setRI(0.05);
    }else{
        Board.getShip().setRI(0);
    }
}

这是 up 事件:

    public void actionPerformed(ActionEvent e) {
    if(pressed){
        Board.getShip().setXX(Math.cos(Board.getShip().getRadians()) * Board.getShip().getSpeed());
        Board.getShip().setYY(Math.sin(Board.getShip().getRadians()) * Board.getShip().getSpeed());
    }else{
        Board.getShip().setXX(0);
        Board.getShip().setYY(0);
    }
}

【问题讨论】:

  • 设置一个标志以确定哪个键或方向处于活动状态。在主“游戏循环”中检查标志并应用适当的增量
  • 类似thisthisthis
  • this 这样的东西应该允许你根据你想要应用的角度和增量来计算 x/y 点

标签: java events game-physics key-bindings


【解决方案1】:

火箭队

火箭定义为

// pseudo code 
rocket = {
    mass : 1000,
    position : {  // world coordinate position
         x : 0,
         y : 0,
    },
    deltaPos : {   // the change in position per frame
         x : 0,
         y : 0,
    },
    direction : 0, // where the front points in radians
    thrust: 100, // the force applied by the rockets
    velocity : ?,  // this is calculated 
}  

运动的公式是

deltaVelocity = mass / thrust;

推力的方向是沿着船所指向的方向。由于每帧位置的变化有两个组成部分,并且推力会改变增量,因此施加推力的方式是;

// deltaV could be a constant but I like to use mass so when I add stuff
// or upgrade rockets it has a better feel.
float deltaV = this.mass / this.thrust;
this.deltaPos.x += Math.sin(this.direction) * deltaV;
this.deltaPos.y += Math.cos(this.direction) * deltaV;

当推力增量被添加到位置增量时,结果是船指向的方向上的加速度。

然后您通过 delta pos 更新每一帧的位置。

this.position.x += this.deltaPos.x;
this.position.y += this.deltaPos.y;

随着时间的推移,您可能需要添加一些阻力来减慢船速。您可以添加一个简单的阻力系数

rocket.drag = 0.99;  // 1 no drag 0 100% drag as soon as you stop thrust the ship will stop.

应用拖动

this.deltaPos.x *= this.drag;
this.deltaPos.y *= this.drag;

获取当前速度,尽管在计算中不需要。

this.velocity = Math.sqrt( this.deltaPos.x * this.deltaPos.x + this.deltaPos.y * this.deltaPos.y);

这将产生与游戏 Asteroids 中相同的火箭行为。如果您希望行为更像是水上的船或汽车(即改变方向会改变三角洲以匹配方向),请告诉我,因为这是对上述内容的简单修改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    相关资源
    最近更新 更多