gpt4 book ai didi

java - 在 cos 曲线形状的地面上编码弹跳球

转载 作者:行者123 更新时间:2023-12-01 08:00:46 24 4
gpt4 key购买 nike

我正在制作一个游戏,其中世界是用 cos 函数生成的,它看起来像这样: enter image description here

在任何 x 点,我可以使用函数 Game.getHeight(x); 找到表面的高度;

现在我想制作一个玩家可以发射的球,它会从表面正确弹跳。我的方法适用于约 5% 的反弹(即其他人射击到地面、以不切实际的角度反弹等)。我该如何改进它?我正在使用的代码:

球(子弹)类:

package game;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.state.StateBasedGame;

public class Bullet {

private final static float speed = 400;
private final static float acc = 250;
public final static float radius = 8;

private int changed;
private float x, y, speedx, speedy;


public Bullet (float x, float y, float tx, float ty) {
this.x = x;
this.y = y;
changed = 0;
float angle;
angle = (float) ((float) Math.atan2(y - ty, tx - x) + .5 * Math.PI);
speedx = (float) (Math.sin(angle) * speed);
speedy = (float) (Math.cos(angle) * speed);
}

public void update(GameContainer gc, StateBasedGame game, int delta) {
x += speedx * (float) delta / 1000;
y += speedy * (float) delta / 1000;
speedy += acc * (float) delta / 1000;
}

public void render (Graphics g) {
g.drawOval(x-radius, y-radius, 2*radius, 2*radius);
g.drawLine(x, y, (float) (32*Math.sin(getDirection()) + x), (float) (32*Math.cos(getDirection()) + y));
}

public void setTrajectory (float angle) {
float spd = speedx + speedy;
speedx = (float) (Math.sin(angle) * spd);
speedy = (float) (Math.cos(angle) * spd);
changed += 1;
}

public float getDirection () {
return (float) ((float) Math.atan2(-speedy, speedx) + .5 * Math.PI);
}

public boolean destroy() {
return (changed >= 2); //destroy it after it has bounced off once
}

public float getX() {
return x;
}

public float getY() {
return y;
}

}

游戏更新方法的片段,其中检查碰撞:

if (bullet != null) {

bullet.update(gc, game, delta);
for (float x = bullet.getX() - bullet.radius; x <= bullet.getX()
+ bullet.radius; x++) {
if (Point2D.distance(x, getHeight(x), bullet.getX(),
bullet.getY()) <= bullet.radius) {
float angle;
angle = (float) (Math.atan2(getHeight(x - 1)
- getHeight(x + 1), -2));

angle += (angle - bullet.getDirection());

bullet.setTrajectory(angle);
if (bullet.destroy()) {
bullet = null;
}
break;
}
}

最佳答案

鉴于您的第一个问题可能是子弹与地面之间的碰撞检测,所以当我做了类似的事情时,the separating axis theorem帮了很多忙。

就反作用力而言,这取决于您希望它看起来有多真实。如果你想比较准确,我建议你查一下suvat运动方程,以及与coefficient of restitution有关的事情

如果您想要不太准确,请计算撞击表面的角度,将表面的切线设为 0 度,然后反转关于平面法线的 vector V1 being the original vector, and V2 being the reaction.

关于java - 在 cos 曲线形状的地面上编码弹跳球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25448528/

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