簡體   English   中英

移動時改變方向

[英]Changing direction while moving

我正在制作一個帶有太空飛船的游戲,當按下向左鍵和向右鍵時,該飛船將旋轉,而按下向上鍵時,該飛船將向前移動。

目前,該船可以在前進的同時旋轉,但會繼續沿前進的方向旋轉。

我將如何操作以使輪船可以在按住向上鍵的同時改變其移動方向?

這是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);
    }
}

火箭隊

定義為

// 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;

當推力增量與位置增量相加時,結果是沿船指向的方向加速。

然后,每幀都通過增量位置更新位置。

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);

這將產生與游戲《小行星》中相同的火箭行為。 如果您想要的行為更像是在水上或汽車上乘船(即,變化的方向會更改增量以匹配方向),請告訴我,因為這是上述內容的簡單修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM