我成功地在我的小游戏中实施了一个射击机制,但是有一个问题。
如果我的光标远离播放器,子弹的速度会更快,如果光标离播放器更近,则子弹的速度会更慢。
所以我的问题是:如何让子弹始终以相同的速度运行?
链接:
代码(来自Shot.java):
public Shot(World world, Camera camera, float x, float y, int width, int height, Color color, float targetX, float targetY) {
super(world, camera, x, y, width, height, color);
this.targetX = targetX;
this.targetY = targetY;
dx = targetX - x;
dy = targetY - y;
}
@Override
public void render(GameContainer gc, Graphics g) {
g.setColor(color);
g.fillOval(x - camera.getX(), y - camera.getY(), width, height);
}
@Override
public void update(GameContainer gc, int delta) {
x += dx * delta * .005f;
y += dy * delta * .005f;
}
我做到了!这是我的解决方案(感谢 Axis 寻求帮助):
float dx, dy;
Vector2f vector;
public Shot(World world, Camera camera, float x, float y, float targetX, float targetY, int width, int height, Color color) {
super(world, camera, x, y, width, height, color);
dx = targetX - x;
dy = targetY - y;
vector = new Vector2f(dx, dy).normalise();
}
@Override
public void render(GameContainer gc, Graphics g) {
g.setColor(color);
g.fillOval(x - camera.getX(), y - camera.getY(), width, height);
}
@Override
public void update(GameContainer gc, int delta) {
x += vector.getX() * delta * 0.8f;
y += vector.getY() * delta * 0.8f;
}
答案 0 :(得分:1)
你的问题在这里:
public Shot(World world, Camera camera, float x, float y, int width, int height, Color color, float targetX, float targetY) {
super(world, camera, x, y, width, height, color);
this.targetX = targetX;
this.targetY = targetY;
dx = targetX - x;
dy = targetY - y;
}
您的子弹速度取决于距目标的距离。使它成为一个恒定的值。
答案 1 :(得分:1)
首先,我建议切换到矢量类,而不是将所有内容分成x和y。从长远来看,它将为您节省大量时间。
您需要做的就是改变
public Shot(World world, Camera camera, Vector2 pos, int width, int height, Color color, Vector2 target) {
super(world, camera, pos, width, height, color);
this.target = target
//dx = targetX - x; get rid of this
//dy = targetY - y; and this
//add a vector called direction
this.direction = (target - pos).Normalize();
}
@Override
public void update(GameContainer gc, int delta) {
pos += direction * delta * bulletSpeed;
}