import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
import java.awt.*;
public class ShotExample extends JPanel implements Runnable, MouseMotionListener, MouseListener {
private static final long serialVersionUID = 1L;
JFrame frame;
Point target;
double angle;
Shot shot;
boolean fire = false;
public static void main(String[] args) {
new ShotExample(400,400);
}
public ShotExample(int i, int j) {
frame = new JFrame("ShotExample");
frame.setLocationRelativeTo(null);
setPreferredSize(new Dimension(i,j));
addMouseMotionListener(this);
addMouseListener(this);
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
target = new Point(0,0);
fire = false;
Thread th = new Thread(this);
th.start();
}
public void run() {
long last = 0;
long delta = 0;
last = System.nanoTime();
while(frame.isVisible()){
delta = System.nanoTime() - last;
last = System.nanoTime();
computeAngle();
checkShot();
if(shot!=null){
shot.move(delta);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
repaint();
}
}
private void computeAngle(){
double dx = target.getX();
double dy = getHeight()-target.getY();
//Java rechnet mit Radians, daher Tangens nach Grad umrechnen
angle = Math.toDegrees(Math.atan2(dx, dy));
}
private void checkShot(){
if(!fire){
return;
}
fire = false;
shot = new Shot(0,getHeight(),angle);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
if(shot!=null){
g.drawRect((int)shot.x,(int)shot.y,(int)shot.width,(int)shot.height);
}
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
target = e.getPoint();
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
fire = true;
}
}
class Shot extends Rectangle2D.Double{
private static final long serialVersionUID = 1L;
final static int SIZE = 10;
final static int SPEED = 200;
double dx;
double dy;
public Shot(int sx, int sy, double dir){
super(sx-SIZE/2,sy-SIZE/2,SIZE,SIZE);
computeDeltas(dir);
}
private void computeDeltas( double d){
//Sinus u. Cosinus ausrechnen. Hypothenuse ist die Geschwindigkeit
//evtl. einfach mal ausmalen
dx = Math.sin(Math.toRadians(d)) * SPEED;
dy = Math.cos(Math.toRadians(d)) * SPEED;
dy *= -1; //Bewegung nach oben - daher y invertieren
}
public void move(long delta) {
if (dy != 0) {
y += dy * (delta / 1e9);
}
if (dx != 0) {
x += dx * (delta / 1e9);
}
}
}