首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >创建一个“项目”类(Java/swing)

创建一个“项目”类(Java/swing)
EN

Stack Overflow用户
提问于 2013-07-02 13:17:46
回答 3查看 2.7K关注 0票数 0

我试图创造一个塔防御风格的游戏,在那里的目标是阻止攻击部队到达他们的目标。这是通过建造塔楼来实现的,它以不同的攻击方式攻击敌人的波涛。由于我刚开始编程,我希望在创建我的SetBulletLocation方法方面能得到一些帮助。

我一直试图复制:this example,但我无法让子弹顺利地朝目标位置移动,

代码语言:javascript
运行
复制
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);
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-07-02 13:28:25

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

双xDirection = 5* Math.cos(-(Math.atan2(tx,tx ))+ 90); 双yDirection = 5* Math.sin(-(Math.atan2(tx,tx ))+ 90);

票数 2
EN

Stack Overflow用户

发布于 2013-07-02 13:40:05

我注意到在计算位移时有错误

碎片:

代码语言:javascript
运行
复制
Math.atan2(tx - x, tx - y))

你不是说吗?:

代码语言:javascript
运行
复制
Math.atan2(tx - x, ty - y))
票数 1
EN

Stack Overflow用户

发布于 2013-07-02 13:41:23

您的paintComponent()似乎每次都在相同的位置和大小上绘制子弹,而不管您的计算如何。

将新的x和新y值存储到成员变量中,并在paintComponent中使用这些变量。

另外,Java的trig函数使用的是弧度,而不是度,所以用pi / 2将引用更新到90度。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17426686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档