0

我正在用 Java(uni 项目)制作一个 2D 自上而下的射击游戏,但遇到了子弹瞄准的问题——我不确定为什么角度不正确,以及如何纠正它。

玩家在鼠标按下时在光标位置射击子弹。我正在使用 dx/y = (x/ytarget - x/yorigin),在每个刻度上用 dx 标准化和递增子弹 x/y pos。

当光标移动时,发射角度会跟踪光标 - 但角度偏离了 45 度左右。白色圆圈是玩家,红色是光标,黄色圆点是子弹。

我没有代表发布图像(第一篇文章),这是一个显示角度错误的链接。

http://i.imgur.com/xbUh2fX

这是子弹类:

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

}

}

4

1 回答 1

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;

}

}
于 2017-03-15T19:14:58.690 回答