So I offered some of my code and was called on it. Turns out my core code is now all 3d with Quaternions etc. However 2d is even easier to avoid trig and even inverse trig. Done right you don’t need all that many sqrts, but even then they are pretty fast.
The idea is simple. A complex number simply represents a unit vector in the direction the angle represents. Turns out complex multiplication is the same as adding angles and complex division is the same as subtracting angles. Since if we start with normalized values we end up with normalized values. Sure there is a little error. You can see that with the java2d demo that is included. You can even compare angles to see which is larger or smaller. Like atan2 angles are implied to be signed ±PI.
In the example the sweeping line is red when smaller than angle to the mouse and blue when larger. It turns green when its in the “acceptance cone”, in this case ±8deg. Finally the funny cyan lines demonstrate interpolation.
Sorry i can’t work out how to put this in a scroll box.
This code has not been unit tested. Use any way you want. I take no responsibility for this code, use at your own risk. And its in the public domain.
import static java.lang.Math.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* other code has too much noise. This is suppose to be clean and make it easy for the jgo use. I use a demo java2d example. We use the convention that x is the
* real axis and y is the imaginary axis.
*
* Note that i assume things are normalized a lot. Since this always represents an angle then this should always have unit length.
*
* Numerical errors for doubles are rather low. But they will eventrually accumulate. But its not like you need to normalize after every operation.
*
* Some degen cases are not checked. In particular you can create a NaN,NaN angle if you create an angle with 0,0.
*
* @author bob
*
*/
public class ComplexAngle implements Comparable<ComplexAngle> {
/**
* Warning these are mutatable.
*/
public static final ComplexAngle DELTA_ANGLE = createAngle(PI * 2 / 720);//1/2 def
public static final ComplexAngle RIGHT_ANGLE=createAngle(PI/2);
private double real = 1;
private double imag = 0;
private ComplexAngle(double r, double i) {
real = r;
imag = i;
}
public static ComplexAngle angleTo(Point2D from, Point2D to) {
return createAngle(to.getX() - from.getX(), to.getY() - from.getY());
}
public static ComplexAngle createAngle(double x, double y) {
ComplexAngle ca = new ComplexAngle(x, y);
ca.normalize();
return ca;
}
public static ComplexAngle createAngle(double rad) {
ComplexAngle ca = new ComplexAngle(Math.cos(rad), Math.sin(rad));
return ca;
}
public ComplexAngle addAngleThis(ComplexAngle c) {
return multiplyThis(c);
}
public ComplexAngle addAngle(ComplexAngle c) {
return multiply(c);
}
/**
* adds angles.
*
* @param c
*/
public ComplexAngle multiplyThis(ComplexAngle c) {
double nr = real * c.real - imag * c.imag;
double ni = real * c.imag + imag * c.real;
real = nr;
imag = ni;
// Normalized since both should be length 1. This adds the angles.
return this;
}
public ComplexAngle multiply(ComplexAngle c) {
double nr = real * c.real - imag * c.imag;
double ni = real * c.imag + imag * c.real;
return new ComplexAngle(nr, ni);
}
public ComplexAngle subtractAngleThis(ComplexAngle c) {
return divideThis(c);
}
public ComplexAngle subtractAngle(ComplexAngle c) {
return divide(c);
}
/**
* subtracts angles.
*
* @param c
*/
public ComplexAngle divideThis(ComplexAngle c) {
double nr = real * c.real + imag * c.imag;
double ni = c.real * imag - c.imag * real;
// since we assume normalized we don't need to divide by
// c.real*c.real+c.imag*c.imag, since that is 1.
real = nr;
imag = ni;
return this;
}
public ComplexAngle divide(ComplexAngle c) {
double nr = real * c.real + imag * c.imag;
double ni = c.real * imag - c.imag * real;
return new ComplexAngle(nr, ni);
}
/**
* compare the angle. If o is bigger that means its a bigger angle. Note this is signed angles.
*
* So we are comparing y/x >=< y'/x'. To avoid degenrancy with x->0 we rearange for y*x' >=< y'*x
*/
@Override
public int compareTo(ComplexAngle o) {
double a = imag*o.real;
double b = o.imag*real;
if (a > b)
return 1;
if (a < b)
return -1;
return 0;
}
/**
* note that we are using signed angles +-PI
*
* @param coneHalfAngle
* @param from
* @param to
* @return
*/
public boolean isInConeAngle(ComplexAngle coneHalfAngle, ComplexAngle angle) {
// need to "rotate" our gun to match the ship
ComplexAngle larger = this.addAngle(coneHalfAngle);
ComplexAngle smaller = this.subtractAngle(coneHalfAngle);
return larger.compareTo(angle) > 0 && smaller.compareTo(angle) < 0;// signed angles
}
/**
* to show the round of errors.
*
* @return
*/
public double length() {
return sqrt(real * real + imag * imag);
}
/**
* I hope this is normalized... Or there will be trouble.
*
* @return
*/
public double cos() {
return real;
}
/**
* we are normlaized... Right!
*
* @return
*/
public double sin() {
return imag;
}
public double tan() {
return imag / real;
}
/**
*
* @return a rotation matrix
*/
public AffineTransform getRotationTransform() {
double cos = real;
double sin = -imag;//for the left handed coords for java2d. Note that a gl matrix would have this +
return new AffineTransform(new double[] { cos, -sin, sin, cos});
}
/**
* degenrate cases when angles are PI apart.
* @param c
* @param t
* @return
*/
public ComplexAngle interpolate(ComplexAngle c, double t) {
double oneMinusT = 1 - t;
double r = real * oneMinusT + c.real * t;
double i = imag * oneMinusT + c.imag * t;
ComplexAngle ca = new ComplexAngle(r, i);
ca.normalize();// typically required here.
return ca;
}
public void normalize() {
double n = 1.0 / Math.sqrt(real * real + imag * imag);
real *= n;
imag *= n;
}
@Override
public String toString() {
return "ComplexAngle("+real+","+imag+"):"+length();
}
public static class Example extends JPanel implements MouseMotionListener{
Point2D mouse=new Point2D.Double(0,0);
ComplexAngle sweep=ComplexAngle.createAngle(1, 0);
Point2D center=new Point2D.Double(100,100);
ComplexAngle cone=ComplexAngle.createAngle(PI*2/45);//8 deg
double t=.5;
double dt=.02;
public Example() {
addMouseMotionListener(this);
setBackground(Color.white);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
t+=dt;
if(t>1){
t=1;
dt=-dt;
}else if(t<0){
t=0;
dt=-dt;
}
ComplexAngle lookAt=ComplexAngle.angleTo(center, mouse);
AffineTransform rotation=lookAt.getRotationTransform();
AffineTransform af=AffineTransform.getTranslateInstance(center.getX(), center.getY());
af.concatenate(rotation);
AffineTransform oldTransform=g2d.getTransform();
g2d.setTransform(af);
g2d.setColor(Color.BLACK);
paintDude(g2d);
//now for sweeper.
if(sweep.compareTo(lookAt)<0){
sweep.addAngleThis(ComplexAngle.DELTA_ANGLE);
g2d.setColor(Color.RED);
}else{
sweep.subtractAngleThis(ComplexAngle.DELTA_ANGLE);
g2d.setColor(Color.BLUE);
}
if(lookAt.isInConeAngle(cone, sweep)){
g2d.setColor(Color.GREEN);
}
System.out.println(sweep);
g2d.setTransform(oldTransform);
drawLine(g2d,center,sweep,200);
g2d.setColor(Color.GRAY);
drawLine(g2d,center,lookAt.addAngle(cone),100);
drawLine(g2d,center,lookAt.subtractAngle(cone),100);
g2d.setColor(Color.CYAN);
drawLine(g2d,center,sweep.interpolate(sweep.addAngle(ComplexAngle.RIGHT_ANGLE),t),50);
drawLine(g2d,center,sweep.interpolate(sweep.subtractAngle(ComplexAngle.RIGHT_ANGLE),t),50);
}
/**
* paints a circle with a line from 0,0 to 10,0
*/
private void paintDude(Graphics2D g2d){
g2d.draw(new Ellipse2D.Double(-10,-5,20,10));
g2d.drawLine(0, 0, 30, 0);
}
private void drawLine(Graphics2D g2d,Point2D from,ComplexAngle angle,double l){
//here we use the example that a complex number can just be interpreted as a unit vector in the direction its pointing.
//this is why, if we are normalized cos and sin are just the real and imag parts respectively.
g2d.drawLine((int)from.getX(),(int)from.getY(),(int)(l*angle.cos()+from.getX()), (int)(l*angle.sin()+from.getY()));
}
@Override
public void mouseDragged(MouseEvent e) {
center=new Point2D.Double(e.getX(),e.getY());
}
@Override
public void mouseMoved(MouseEvent e) {
mouse=new Point2D.Double(e.getX(),e.getY());
}
}
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
Example example=new Example();
frame.add(example);
frame.setVisible(true);
((Graphics2D)example.getGraphics()).addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
while(true){
try {
Thread.sleep(16);
} catch (InterruptedException e) {
e.printStackTrace();
}
example.repaint();
}
}
}