Hi.
I am making a really simple program to refresh my knowledge in java (which is obviously needed). When I click the screen, I want a bullet to appear in the center and move towards the point I clicked. Right now, when I click on the left half the bullet will go either straight up or directly left, and if I click the right half then it just stays in the center of the screen.
I have two classes (plus a third main class):
ShooterPanel class
package shooter;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class ShooterPanel extends JPanel implements Runnable, MouseListener {
boolean gameOver;
int aimFPS = 60;
int mouseX;
int mouseY;
boolean hasShot;
Thread t = new Thread(this);
Bullet[] bullets = new Bullet[100];
public ShooterPanel(){
addMouseListener(this);
t.start();
}
public void fireShots(){
if(hasShot){
for(int i = 0; i < bullets.length; i++){
if(bullets[i] == null){
bullets[i] = new Bullet(200, 200, mouseX, mouseY);
double angle = Math.atan2(bullets[i].targetY - bullets[i].posY, bullets[i].targetX - bullets[i].posX);
if(angle < 0){
angle += 360;
}
bullets[i].setAim(angle);
System.out.println("Created a new bullet object");
break;
}
}
hasShot = false;
}
}
public void moveBullets(){
for(Bullet bullet : bullets){
if(bullet != null){
bullet.move();
System.out.println("New bullet position is [" + bullet.posX + ", " + bullet.posY + "]");
}
}
}
@Override
public void paintComponent(Graphics gc){
super.paintComponent(gc);
for(Bullet bullet : bullets){
if(bullet != null){
gc.setColor(Color.BLACK);
gc.fillOval(bullet.posX, bullet.posY, 7, 7);
System.out.println("Drew a bullet");
}
}
gc.setColor(Color.BLACK);
gc.fillOval(50, 50, 20, 20);
gc.drawString("Hiya", 80, 80);
}
@Override
public void run(){
while(!gameOver){
fireShots();
moveBullets();
repaint();
try{
Thread.sleep(1000 / aimFPS);
}catch(InterruptedException ie){
t.interrupt();
System.out.println("Couldn't pause thread");
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
hasShot = true;
System.out.println("Heard mouse realease at [" + mouseX + ", " + mouseY + "]");
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
Bullet class
package shooter;
public class Bullet {
int posX;
int posY;
int targetX;
int targetY;
double aim;
public Bullet(int posX, int posY, int targetX, int targetY){
this.posX = posX;
this.posY = posY;
this.targetX = targetX;
this.targetY = targetY;
}
public double getAim(){
return aim;
}
public void setAim(double angle){
this.aim = angle % (2 * Math.PI);
}
public void move(){
double stepX = Math.cos(getAim());
double stepY = Math.sin(getAim());
posX += stepX;
posY += stepY;
}
}