Home > Blockchain >  Bullets become super fast as the angle gets closer 90
Bullets become super fast as the angle gets closer 90

Time:11-27

so I'm developing a game in Java and I'm trying to shoot bullets towards the cursor position- the shooting part is OK but as the angle between the cursor and the player (the player shoots the bullets so essentially its the bullet's first coordinates) get closer to 90 (or -90) the bullets going super fast and I have no idea why

The red zone is the super-speed zone

Code:

    public void run() {
        super.run();
        final double currentY=y;
        final double currentX=x;

        double slope = (cursorPos.y - currentY) / (cursorPos.x - currentX);
        double angle= Math.toDegrees(Math.atan2(cursorPos.y - currentY, cursorPos.x - currentX));
        System.out.println(angle);
        while (true){
            try {
                double newY;// y = m * (x-x.)   y.
                newY = ((slope*(x - currentX)) currentY);
                y= (int) newY;
                if ((angle <=-90 && angle>=-180) || (angle >=90 && angle<=180) )
                {
                    x--;
                }
                else {
                    x  ;
                }
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

CodePudding user response:

You're stepping x in time by fixed increments of one. So when the bullet lines are near vertical, the slope m is a big number, and they're covering m pixels per step in y. The closer to vertical, the faster they go.

Instead you need to step in fixed increments of distance along the line segment the bullet is following. If the endpoints are (x0,y0) and (x1,y1), then varying t from 0 to 1 in the equations x = t*(x1-x0) x0; and y=t*(y1-y0) y0 will sweep the line segment. To sweep by units of 1 pixel, you need to know how many pixels there are along the line. That's L = sqrt(sqr(x1-x0) sqr(y1-y0)), so the values of t are i / L for i = 0 to L.

You'll need to do these computations with floating point numbers.

Another note is that you'll probably eventually have trouble using Sleep as you are. This prevents the Swing event handling loop from doing any work while it's waiting.

  • Related