问题:
我成功地在我的小游戏中实现了射击机制,但有一个问题。
如果我的光标离玩家较远,子弹的速度会更快;如果光标离玩家较近,子弹的速度会较慢。
所以我的问题是:如何让子弹始终以相同的速度移动?
链接:
代码(来自 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;
}
最佳答案
首先,我建议切换到 vector 类,而不是将所有内容拆分为 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;
}
关于java - 光滑2d |以相同的速度射击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15990051/