I need to have the user control the image via WASD keys to move around the screen. I have gotten this to work with a paint generated “rect” but can’t seem to get it to work with a gif image. I am still a beginner and am not the best coder.
NOTE: I have the gif saved onto my desktop. Will that affect my code?
Here’s my code:
package maze;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Maze extends JApplet implements KeyListener
{
int x;
int y;
public void init()
{
setBackground(Color.black);
x = 20;
y = 20;
addKeyListener(this);
Image img;
img = getImage(getCodeBase(), "soldier.gif");
setVisible(true);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e)
{
char c = e.getKeyChar();
if (c == 'w')
{
y -= 20;
}
else if (c == 's')
{
y += 20;
}
else if (c == 'a')
{
x -= 20;
}
else if (c == 'd')
{
x += 20;
}
if (c != KeyEvent.CHAR_UNDEFINED)
{
repaint();
e.consume();
}
}
public void paint(Graphics g)
{
requestFocus(); // applet's initial focus
g.drawImage(img,50,50, this);
if (!collisionDetection())
{
g.setColor(Color.gray);
g.drawLine(0, 100, 250, 100);
}
else
{
g.setColor(Color.yellow);
g.drawString("LOSER", 130, 150);
}
}
public boolean collisionDetection()
{
if (x < 250 && y < 100 && y + 20 > 100) // line segment 1
{
return true;
}
return false;
}
public class DisplayImage extends JApplet
{
private Image img;
public void init()
{
img = getImage(getDocumentBase(),"soldier.gif");
}
public void paint(Graphics g)
{
g.drawImage(img, 50, 50, this);
}
}
}
The g.drawImage(img,50,50, this); above the collision if statement is giving me an error for “img”… Saying “Cannot find symbol” - “Symbol: variable img”. Not sure what is the problem. Help much appreciated. Thanks!