简体   繁体   English

子弹射击目标算法-Java

[英]Bullet Shooting On Target Algorithm - Java

I am making a game where you can shoot. 我正在制作一个可以射击的游戏。 I am having a problem with my algorithm, the bullet is pointing in the direction of the mouse but not moving towards it. 我的算法有问题,项目符号指向鼠标的方向,但没有朝鼠标的方向移动。 Can you please provide me with a better algorithm and tell me why mine does not work? 您能否为我提供更好的算法,并告诉我为什么我的系统不起作用? All of this code is in Java. 所有这些代码都使用Java。 BTW the class MImage is a class that I made so don't get confused by it. 顺便说一句,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);
            }
        }

` `

And here is when i make a new instance of the class 这是当我创建该类的新实例时

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;
}

THANK YOU 谢谢

I found an answer to my question. 我找到了问题的答案。 The Algorithm is not hard at all, but it's not perfect but still works. 该算法一点都不难,但并不完美,但仍然有效。 It's simple Trigonometry... if you let angle = Math.atan2(dy,dx) then velocityX = speed*Math.cos(angle) and let velocityY = speed*Math.sin(angle) then in the update function put this code x += velocityX y+= velocityY 这是简单的三角函数...如果让angle = Math.atan2(dy,dx)然后把velocityX = speed*Math.cos(angle) ,让velocityY = speed*Math.sin(angle)然后在更新函数中输入此代码x += velocityX y+= velocityY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM