在Java中,要實現正方形和圓形的碰撞檢測,可以使用以下方法:
class Square {
double x;
double y;
double width;
double height;
}
class Circle {
double x;
double y;
double radius;
}
public class CollisionDetector {
public static boolean isColliding(Square square, Circle circle) {
// 計算正方形的中心點
double squareCenterX = square.x + square.width / 2;
double squareCenterY = square.y + square.height / 2;
// 計算圓心到正方形中心點的向量
double vectorX = circle.x - squareCenterX;
double vectorY = circle.y - squareCenterY;
// 計算圓心到正方形邊界的最短距離
double distanceX = Math.abs(vectorX) - square.width / 2;
double distanceY = Math.abs(vectorY) - square.height / 2;
// 如果圓心到正方形邊界的距離都小于等于圓的半徑,則發生碰撞
return (distanceX <= circle.radius) && (distanceY <= circle.radius);
}
}
CollisionDetector
類的isColliding
方法來檢測正方形和圓形是否發生碰撞。public class Main {
public static void main(String[] args) {
Square square = new Square();
square.x = 0;
square.y = 0;
square.width = 100;
square.height = 100;
Circle circle = new Circle();
circle.x = 50;
circle.y = 50;
circle.radius = 50;
boolean isColliding = CollisionDetector.isColliding(square, circle);
System.out.println("Is colliding? " + isColliding);
}
}
這個示例中,正方形和圓形發生了碰撞,輸出結果為Is colliding? true
。你可以根據需要修改正方形和圓形的位置和大小來測試不同的情況。