如何将矩形变成四条线,然后找到这些线与其他线的交点?

时间:2019-04-01 18:59:27

标签: java

完整的问题:如何将矩形变成四条线,然后判断其中一条线是否与构成赛马场的线相交?我正在制作一款赛车游戏,玩家可以在其中旋转矩形

这是我的代码:

public void show(Graphics2D g) {

    Graphics2D g2d = (Graphics2D) g; // Car
    AffineTransform old = g2d.getTransform();
    AffineTransform newT = g2d.getTransform();
    g2d.setTransform(newT);

    newT.setToRotation(Math.toRadians(rotation),  this.x + this.width / 2,  this.y + this.height / 2);

    g2d.transform(newT);
    g2d.drawImage(car, (int) this.x, (int) this.y, (int) 50, (int) 75, Runner.frame);
    g.setColor(Color.PINK);
    g2d.setTransform(old);
}
 public Line2D[] getEdges(){
    Line2D edges[] = new Line2D.Double[4]; //Four lines of rectangle
    Line2D length = new Line2D.Double();
    double startX = getX()+getWidth(); 
    double startY = getY();
    double endX  = getX()+getWidth();   
    double endY = getY()+getHeight();
    length.setLine(startX, startY, endX, endY);  

    edges[0] = height; //other lines that I cant get to work 
    edges[1] = height2;
    edges[2] = length; //The main Line I'm trying to work on
    edges[3] = length2;

    return edges;
 }




 public void drawLines(Graphics2D g2d){ //Where I draw the lines
     AffineTransform at = AffineTransform.getRotateInstance( Math.toRadians(getRotation()), r[2].getX1(), r[2].getY1());
    Shape newLine = at.createTransformedShape(r[2]);
    g2d.draw(newLine);
   }

1 个答案:

答案 0 :(得分:0)

如果您的轨道是由简单的多边形组成的(例如,没有曲线),则可以将轨道边界的所有坐标存储在一个数组中。 然后,在每帧上,检查矩形的每个角是否在此边界内。 如果是,那么您就很好。 如果不是,那么您就崩溃了。 请记住,这是冲突检测的一种非常简单的形式,但是会做得很好。 Here是一个很好的例子(可在checkCollisions()方法中找到)。

相关问题