-1

I'm using Java Rectangles in my game in order to check collision between objects (using the intersects() method). As far as I know, this cannot be done if one of the objects is rotated.

Say, for example, one of the objects in the game is rotated 65°. How would I go about checking collision on this object? Is there a way I can add rotation to its Rectangle? If not, is there a way I can check collision without using Rectangles (using e.g. pixel colors)?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Soni
  • 77
  • 1
  • 10
  • 1
    Have you tried using pencil and paper, drawing two rectangles, one rotated an one not, and coming up with an algorithm? Then translate that into your own `intersects` method. That is how most problems like this would be solved. – WJS Dec 20 '20 at 20:05
  • Does this answer your question? [Java collision detection between two Shape objects?](https://stackoverflow.com/questions/15690846/java-collision-detection-between-two-shape-objects) – tucuxi Dec 21 '20 at 12:26
  • I have voted this as a duplicate for shape rotation, because if you use Java Shapes (of which Rectangles are a special case), you have built-in collision detection, regardless of rotation. – tucuxi Dec 21 '20 at 12:27
  • @gpash you need segment intersection if you want to do it right: picture two elongated rectangles making an X, where no point of either rectangle is inside the other. Note that you need segments, and line intersection is not enough: picture those same segments, forming a T where the top does not touch the stem. – tucuxi Dec 21 '20 at 23:41

1 Answers1

2

Perhaps you should provide more information about your project, even by showing us a few lines of code. Anyway, if you are working with Cartesian plane, one way to rotate a point is this:

    public Point ruota(double alpha, Point r){
      double qx = r.x + (x - r.x) * Math.cos(alpha) - (y - r.y)* Math.sin(alpha);
      double qy = r.y + (x - r.x) * Math.sin(alpha) + (y - r.y)* Math.cos(alpha);
      return new Point(qx, qy);
    }
  • I haven't worked with Points before, so just as an example - would this create a rectangle that is rotated 45°? Rectangle r = new Rectangle(new Point(100, 100)); r.add(new Point(150, 50)); r.add(new Point(200,100)); r.add(new Point(150, 150)); – Soni Dec 21 '20 at 11:42
  • 1
    A rotation requires a center of rotation. You are using r as a center there, and your code is missing arguments `x` and `y`, the coordinates for the point you are rotating. – tucuxi Dec 21 '20 at 12:23
  • @tucuxi If you are referring to my code, r is an instance of Point class: x and y do not need to be defined in this method. – Chiara Tumminelli Dec 21 '20 at 19:24
  • Ah. There is a [Point](https://docs.oracle.com/javase/7/docs/api/java/awt/Point.html) class already in `java.awt`, and I thought you were using it instead of writing your own. – tucuxi Dec 21 '20 at 23:38