I'm trying to teach myself java and I "try" to code a little game.
I have a problem and I guess the solution is very simple but I'm struggling.
The basic idea is that I am controlling a circle and I want to spawn circles every 5 seconds at random locations within the boundries of my window . The circles should move towords the location of the circle that I'm controlling.
Here's what I have so far:
Window-Class:
package TestGame;
import java.awt.Graphics;
public class Window extends GameIntern{
public void init(){
setSize(854,480);
Thread th = new Thread(this);
th.start();
offscreen = createImage(854,480);
d = offscreen.getGraphics();
addKeyListener(this);
}
public void paint(Graphics g){
d.clearRect(0,0,854,480);
d.drawOval(x, y, 20, 20);
g.drawImage(offscreen,0,0,this);
}
public void update(Graphics g){
paint(g);
}
}
GameIntern-Class:
package TestGame;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class GameIntern extends Applet implements Runnable , KeyListener {
public int x,y;
public Image offscreen;
public Graphics d;
public boolean up,down,left,right;
public void run() {
x = 100;
y = 100;
while(true){
if(left == true){
if(x>=4){
x-=4;
}else{ x=0;}
repaint();
}
if(right == true){
if(x<=826){
x+=4;
}else{ x=830;}
repaint();
}
if(up == true){
if(y>=4){
y-=4;
}else{ y=0;}
repaint();
}
if(down == true){
if(y<=454){
y+=4;
}else{y=459;}
repaint();
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 37){
left=true;
}
if(e.getKeyCode() == 38){
up=true;
}
if(e.getKeyCode() == 39){
right=true;
}
if(e.getKeyCode() == 40){
down=true;
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 37){
left=false;
}
if(e.getKeyCode() == 38){
up=false;
}
if(e.getKeyCode() == 39){
right=false;
}
if(e.getKeyCode() == 40){
down=false;
}
}
public void keyTyped(KeyEvent e){}
}
I know it's nothing fancy but I'm struggling with how to create and spawn the "enemy"-circles and how to controll the x/y values of every single created circle to move towards the controllable circle.
Any form of help is appreciated.