简体   繁体   English

随着角度接近 90,子弹变得超级快

[英]Bullets become super fast as the angle gets closer 90

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因此,我正在开发Java的游戏,我正在尝试向Z1791A97A97A8403730EE0760489A2AEB992Z位置射击子弹,但射击部分是Z17991A.991A的射击部分,是射击部门。 ) 接近 90 (或 -90) 子弹速度超快,我不知道为什么

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

You're stepping x in time by fixed increments of one.您按固定增量 1 在时间上步进 x。 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.所以当子弹线接近垂直时,斜率 m 是一个很大的数字,它们在 y 中每步覆盖 m 个像素。 The closer to vertical, the faster they go.越接近垂直,它们 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;如果端点是 (x0,y0) 和 (x1,y1),则在方程 x = t*(x1-x0)+x0 中将 t 从 0 变为 1; and y=t*(y1-y0)+y0 will sweep the line segment.并且 y=t*(y1-y0)+y0 将扫描线段。 To sweep by units of 1 pixel, you need to know how many pixels there are along the line.要以 1 个像素为单位进行扫描,您需要知道沿线有多少个像素。 That's L = sqrt(sqr(x1-x0) + sqr(y1-y0)), so the values of t are i / L for i = 0 to L.那就是 L = sqrt(sqr(x1-x0) + sqr(y1-y0)),所以对于 i = 0 到 L,t 的值是 i / 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.另一个注意事项是,您最终可能会在使用 Sleep 时遇到问题。 This prevents the Swing event handling loop from doing any work while it's waiting.这可以防止 Swing 事件处理循环在等待时执行任何工作。

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

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