gpt4 book ai didi

java - 移动时改变方向

转载 作者:行者123 更新时间:2023-12-01 10:37:52 26 4
gpt4 key购买 nike

我正在制作一个 spaceship 游戏,按下左右键时它会旋转,按下向上键时它会向前移动。

目前,船舶在前进时可以旋转,但它将继续朝前进的方向行驶。

我该如何做才能让船在按住向上键的同时改变其移动方向?

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

这是向上事件:

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

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

关于java - 移动时改变方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com