我正在使用Java(uni项目)制作2D自上而下的射击游戏,但遇到了子弹瞄准的问题 - 我不确定为什么角度不正确,以及如何纠正它。
玩家在mousedown的光标位置射击子弹。我正在使用dx / y =(x / ytarget - x / yorigin),使用每个刻度dx标准化和递增子弹x / y pos。
当光标移动时,触发角度跟踪光标 - 但角度偏离45度左右白色圆圈是播放器,红色是光标,子弹是黄色圆点。
我没有代表发布图片(第一篇文章),这里是一个显示角度误差的链接。
这是子弹类:
注意 - 主游戏循环
调用update()import java.awt.*;
import java.awt.MouseInfo;
public class Bullet {
private double x;
private double y;
private int r;
private double dx;
private double dy;
private double speed;
private double angle;
private Point c;
private Color color1;
public Bullet(int x, int y) {
this.x = x;
this.y = y;
r = 3;
speed = 30;
color1 = Color.YELLOW;
c = MouseInfo.getPointerInfo().getLocation();
// getting direction
dx = c.x - x;
dy = c.y - y;
double distance = Math.sqrt(dx*dx + dy*dy);
dx /= distance;
dy /= distance;
}
public boolean update() {
x += dx*speed;
y += dy*speed;
if(x < -r || x > GamePanel.WIDTH + r ||
y < -r || y > GamePanel.HEIGHT + r) {
return true;
}
return false;
}
public void draw(Graphics2D g) {
g.setColor(color1);
g.fillOval((int) (x - r), (int) (y - r), 2 * r, 2 * r);
}
}
答案 0 :(得分:0)
我有一个类似的游戏,这是我使用的代码
import java.awt.Graphics2D;
import araccoongames.pongadventure.game.Entity;
import araccoongames.pongadventure.game.Game;
import araccoongames.pongadventure.game.MapLoader;
public class Ball extends Entity {
private float speed = 8;
private float speedx;
private float speedy;
private float degree;
public Ball(float posx, float posy, Game game) {
super(0, 0, game);
this.posx = posx;
this.posy = posy;
// posx = ball x position
// posy = ball y position
// game.input.MOUSEY = mouse y position
// game.input.MOUSEX = mouse x position
degree = (float) (270 + Math.toDegrees(Math.atan2(posy - game.input.MOUSEY, posx - game.input.MOUSEX))) % 360;
speedx = (float) (speed * Math.sin(Math.toRadians(degree)));
speedy = (float) (speed * Math.cos(Math.toRadians(degree)));
}
@Override
public void render(Graphics2D g) {
drawImage(game.texture.SPRITE[0][1], g);
}
@Override
public void update() {
posx += speedx;
posy -= speedy;
}
}