java - 创建 "bullet"类(Java/swing)

标签 java swing class projectile

我正在尝试创建一款塔防风格的游戏,其目标是阻止攻击部队到达目标。这是通过 build 塔楼来完成的,塔楼会用不同类型的攻击来攻击一波又一波的敌人。由于我是编程新手,我希望在创建子弹的 SetBulletLocation 方法方面获得一些帮助。

我一直在尝试复制:this example但我无法让我的子弹顺利地飞向目标位置

public class Bullets extends JComponent{
//x,y = the towers coordinates, where the shoot initiliazes from.
//tx, ty = Target's x and y coordinates.
private int x,y,tx,ty;
private Point objectP = new Point();
    public Bullets(int x, int y, int tx, int ty)
        this.x = x;
        this.y = y;
        this.tx = tx;
        this.ty = ty;
        setBounds(x,y,50,50);
        //Create actionlistener to updateposition of the bullet (setLocation of component)
        ActionListener animate = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {

            setBulletLocation();


        }
        };
        Timer t = new Timer(500,animate);
        t.start();

    }
public void setBulletLocation() {
    objectP = this.getLocation();
    double xDirection =  5* Math.cos(-(Math.atan2(tx - x, tx - y))+ 90);
    double yDirection =  5* Math.sin(-(Math.atan2(tx - x, tx - y))+ 90);
    System.out.println(xDirection + " , " + yDirection);
    x = (objectP.x + (int) xDirection);
    y = (objectP.y + (int) yDirection);
    setLocation(x, y);

    repaint();
 }
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fillOval(0, 0, 50, 50);
}

最佳答案

所有 Java 数学三角函数都采用弧度作为角度参数,而不是度数。尝试使用 Math.PI/2 而不是 90:

double xDirection = 5* Math.cos(-(Math.atan2(tx - x, tx - y))+ 90);

double yDirection = 5* Math.sin(-(Math.atan2(tx - x, tx - y))+ 90);

关于java - 创建 "bullet"类(Java/swing),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17426686/

相关文章:

java - JTabbedPane触发事件

Java 仿射变换 Scale()

java - 如何在类图中显示静态类

java - 如何在 JavaFX css 中将 -fx-max-width 设置为 USE_PREF_SIZE?

java - 如何在 Spring 应用程序中运行 JFrame?

java - 如何为 Java RPG 游戏制作简单的迷你 map

javascript - Javascript 正则表达式中的元字符与字符范围

java - 锚定 Pane 中元素的顺序

java - 如何避免在 Java 中具有相同方法主体但返回类型不同的重复代码?

c++ - 在 C++ 中的自定义类的构造函数中初始化没有参数的静态 const 类成员