【问题标题】:Bullet Shooting On Target Algorithm - Java子弹射击目标算法 - Java
【发布时间】:2017-09-19 18:47:13
【问题描述】:

我正在制作一款可以射击的游戏。我的算法有问题,子弹指向鼠标的方向,但没有朝它移动。您能否为我提供一个更好的算法并告诉我为什么我的算法不起作用?所有这些代码都是用Java编写的。 顺便说一句,MImage 类是我创建的一个类,所以不要被它弄糊涂了。 `

private double angle;
    public Bullet(int xx, int yy, int x, int y,Gun gun, int id, double angle) {
        this.x = xx;
        this.y = yy;
        tx = x;
        ty = y;
        xorg = xx;
        yorg = yy;
        this.gun = gun;
        this.id = id;
        this.angle = angle;


        try {
            image = new MImage(ImageIO.read(new File("PATH")));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        image.rotateBy((int)Math.toDegrees(angle));

        stopwatch.start();
    }



    private int speed = 3,time = 0;;
        public void update() {


            double speedy, speedx;
            speedy = speed * Math.sin(Math.toRadians(angle));
            speedx = speed * Math.cos(Math.toRadians(angle));

             y = (int) ((-5) * time * time + speedy * time + yorg);
             x = (int) (speedx * time + xorg);
             time++;

             System.out.println(y + " --- " + x);
            if(stopwatch.getElapsedTime() > 500) {
                terminate(id);
            }
        }

`

这是我创建类的新实例的时候

public boolean shoot(int x, int y, int tx, int ty) {
    boolean worked = false;
    if(amo >= 0) {
        bullets.add(new Bullet(x,y,tx,ty,this,bullets.size(),Math.atan2(ty-y,tx-x)));
        amo --;
        worked = true;
    }
    return worked;
}

谢谢

【问题讨论】:

  • 你确定 Unity3D 标签适合这个问题吗?我看不出这与 Unity 游戏引擎有任何关系。
  • 不,但人们可以看到我的问题。这是关于游戏开发的,所以在某些时候你可能想在 C# 中使用这个算法

标签: java algorithm 2d projectile


【解决方案1】:

我找到了问题的答案。该算法一点也不难,但它并不完美,但仍然有效。这是简单的三角函数...如果你让angle = Math.atan2(dy,dx) 然后velocityX = speed*Math.cos(angle) 并让velocityY = speed*Math.sin(angle) 然后在更新函数中输入此代码x += velocityX y+= velocityY

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-13
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多