This returns the collision points between a line and a circle. - Java java.lang

Java examples for java.lang:Math Function

Description

This returns the collision points between a line and a circle.

Demo Code


//package com.java2s;
import java.awt.geom.Line2D;

import java.awt.geom.Point2D.Double;

public class Main {
    /**/*from w  ww.java 2  s  .  c o m*/
     * This returns the collision points between a line and a circle.
     * It has a small toleranz value about 0.3.
     * 
     * @param x1
     *            the x position of point 1.
     * @param y1
     *            the y position of point 1.
     * @param x2
     *            the x position of point 2.
     * @param y2
     *            the y position of point 2.
     * @param xc
     *            the x position of the circle.
     * @param yc
     *            the y position of the circle.
     * @param radius
     *            the radius of the circle.
     * @return a array with collision points.
     */
    public static Double[] circleTest(double x1, double y1, double x2,
            double y2, double xc, double yc, double radius) {

        //TODO ugly hack, fix later...

        final double TOLERANZ = 0.3;

        double baX = x2 - x1;
        double baY = y2 - y1;
        double caX = xc - x1;
        double caY = yc - y1;

        double a = baX * baX + baY * baY;
        double bBy2 = baX * caX + baY * caY;
        double c = caX * caX + caY * caY - radius * radius;

        double pBy2 = bBy2 / a;
        double q = c / a;

        double disc = pBy2 * pBy2 - q;
        if (disc < 0)
            return new Double[] {};

        // if disc == 0 ... dealt with later
        double tmpSqrt = Math.sqrt(disc);
        double abScalingFactor1 = -pBy2 + tmpSqrt;
        double abScalingFactor2 = -pBy2 - tmpSqrt;

        Double p1 = new Double(x1 - baX * abScalingFactor1, y1 - baY
                * abScalingFactor1);
        if (disc == 0) // abScalingFactor1 == abScalingFactor2
            if (Line2D.ptSegDist(x1, y1, x2, y2, p1.x, p1.y) <= TOLERANZ)
                return new Double[] { p1 };
            else
                return new Double[] {};

        Double p2 = new Double(x1 - baX * abScalingFactor2, y1 - baY
                * abScalingFactor2);
        if (Line2D.ptSegDist(x1, y1, x2, y2, p1.x, p1.y) <= TOLERANZ
                && Line2D.ptSegDist(x1, y1, x2, y2, p2.x, p2.y) <= TOLERANZ)
            return new Double[] { p1, p2 };
        else
            return new Double[] {};
    }
}

Related Tutorials