有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用Java绘制一段圆的几何图形?

为了好玩,我正在用Java制作一个砖块破坏游戏。在这个游戏中,球棒是一个围绕圆周的弧形。我正在努力使球棒正常动作。 我正在从圆上的两点绘制一条圆弧:

public void update(){

    if(dir == 1){
        angle += 0.05;
    }else if(dir == 0){
        angle -= 0.05;
    }


    x0 = a + r * Math.cos(angle);
    y0 = b + r * Math.sin(angle);
    x1 = a + r * Math.cos(angle - 0.1);
    y1 = b + r * Math.sin(angle - 0.1);

} 
public void draw(Graphics2D g){
    g.setColor(Color.black);
    g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT);
    int tr = (int)Math.sqrt((x0-a)*(x0-a) + (y0-b)*(y0-b));
    int x = (int) (a - tr);
    int y = (int) (a - tr);
    int width = 2*tr;
    int height = 2*tr;
    int startAngle = (int) (180/Math.PI*Math.atan2(y0-b, x0-a));
    int endAngle = (int) (180/Math.PI*Math.atan2(y1-b, x1-a));
    g.setColor(Color.white);
    g.drawArc(x, y, width, height, startAngle, endAngle);
}

从理论上讲,这应该是可行的,第二个点是从角度稍微进一步生成的,但弧的长度在大小上保持变化。。。?这就是问题所在


共 (1) 个答案

  1. # 1 楼答案

    此here语句打破了这种模式:

    int y = (int) (a - tr);
    

    使用它会更有意义

    int y = (int) (b - tr);
    

    还有一种叫做g.drawArc的方式:

    g.drawArc(x, y, width, height, startAngle, endAngle);
    

    最后一个参数是圆弧的角度,因此我认为您需要

    g.drawArc(x, y, width, height, startAngle, endAngle - startAngle );
    

    甚至可能

    g.drawArc(x, y, width, height, startAngle, Math.abs(endAngle - startAngle) );