So I'm learning up on basic GUI and I wanted to make a basic game with a drawn character that moves left and right and shoots at random targets. I've been thinking about it and can't really figure it out and the chapter in the book i'm reading doesn't really help with this situation. In my code I created a class for the person and used paintcomponent to draw the character. I then created a class for the controls in which I added a keylistener and a keyadapter for the motion controls. I'm not sure if that was right, but I couldn't access the variable outside the class in order to repaint the person. I'm not sure if I was on the right track or not, but I need some help with this.
here's some of my code (controls and person)
class Controls extends JPanel{
public Controls(){
add(new Person());
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT : xHeadCenter += 10; break;
case KeyEvent.VK_LEFT : xHeadCenter -= 10; break;
case KeyEvent.VK_UP : right -= 2; yarms2 -= 2; break;
case KeyEvent.VK_DOWN : right += 2; yarms2 += 2; break;
}
repaint();
}
});
}
}
class Person extends JPanel{
int xHeadCenter = getWidth()/5;
protected void paintComponent(Graphics g){
super.paintComponent(g);
/*Head Construction
* Rest of the body is centered around these two values
*/
int yHeadCenter = (int)(getHeight()*.6);
int radius = (int)(Math.min(getWidth(), getHeight()) * 0.05);
int x = xHeadCenter - radius;
int y = yHeadCenter - radius;
//fill in head
g.fillArc(x, y, 2*radius, 2*radius, 0, 30);
g.fillArc(x, y, 2*radius, 2*radius, 30, 30);
g.fillArc(x, y, 2*radius, 2*radius, 60, 30);
g.fillArc(x, y, 2*radius, 2*radius, 90, 30);
g.fillArc(x, y, 2*radius, 2*radius, 120, 30);
g.fillArc(x, y, 2*radius, 2*radius, 150, 30);
g.fillArc(x, y, 2*radius, 2*radius, 180, 30);
g.fillArc(x, y, 2*radius, 2*radius, 210, 30);
g.fillArc(x, y, 2*radius, 2*radius, 240, 30);
g.fillArc(x, y, 2*radius, 2*radius, 270, 30);
g.fillArc(x, y, 2*radius, 2*radius, 300, 30);
g.fillArc(x, y, 2*radius, 2*radius, 330, 30);
//body
int xbod1 = xHeadCenter;
int xbod2 = xbod1;
int ybod1 = yHeadCenter + radius;
int ybod2 = ybod1 + radius*3;
//draw body
g.drawLine(xbod1, ybod1, xbod2, ybod2);
//arms
int left = x/2 - radius/2;
int right = (int)((xHeadCenter+radius)*1.5);
int yarms = ybod1 + (int)(radius * 0.3);
int yarms2 = ybod1 + (int)(radius * 0.3);
//draw left arm
g.drawLine(left, yarms, xbod1, yarms);
//draw right arm
g.drawLine(xbod1, yarms, right, yarms2);
//legs
int leftleg = x;
int lefty = (int)(ybod2 * 1.25);
int rightleg = xHeadCenter + radius;
int righty = (int)(ybod2 * 1.25);
//left leg
g.drawLine(xbod2, ybod2, leftleg, lefty);
//right leg
g.drawLine(xbod2, ybod2, rightleg, righty);
}
}
}