Monday, June 11, 2018

java - How can I make Diagonal movement?


This is a follow-up question to my last one. I am developing a game which has an Icon on a JLabelwhich the user controls with WASD keys. Right now it can go up, down, left, and right, but I want to know how I can make it move diagonally if two keys are held. I have recreated a short example and posted it below along with a gif(sorry, it's not very smooth), and I am hoping you can help me out. Thanks!


public class Experiments extends JFrame {
javax.swing.Timer movement;

int x = 230;
int y = 120;
boolean wPressed, aPressed, sPressed, dPressed;

public Experiments() {
layoutGame();
setTitle("Example");
setSize(500, 350);
setLocationRelativeTo(null);
setVisible(true);

}

private void layoutGame() {
JLabel bg = new JLabel();
bg.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("space.png")));
add(bg, BorderLayout.CENTER);

JLabel you = new JLabel();
you.setBounds(x, y, 50, 50);
you.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("happy.png")));

bg.add(you, JLabel.CENTER);

JTextPane direction = new JTextPane();
direction.setText("Direction");
add(direction, BorderLayout.SOUTH);
move(you);

direction.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {

movement.stop();
if(e.getKeyChar() == 'w') {
wPressed = true;
move(you);
} else if (e.getKeyChar() == 'a') {
aPressed = true;
move(you);
} else if (e.getKeyChar() == 's') {
sPressed = true;
move(you);

} else if (e.getKeyChar() == 'd') {
dPressed = true;
move(you);
}
direction.setText(null);
}
public void keyReleased(KeyEvent e) {
wPressed = false;
aPressed = false;
sPressed = false;

dPressed = false;
}
});
}

private void move(JLabel icon) {
int delay = 10; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(icon.getX() >= 0 && icon.getX() <= 450 && icon.getY() >= 0 && icon.getY() <= 250) {

if (wPressed) {
y = y - 4;
} else if(aPressed) {
x = x - 4;
} else if(sPressed) {
y = y + 4;
} else if(dPressed) {
x = x + 4;
}
icon.setBounds(x, y, 50, 50);

icon.repaint();
}
}
};
movement = new javax.swing.Timer(delay, taskPerformer);
movement.start();
}

public static void main(String[] args) {
new Experiments();

}
}

The output is smooth, but I had to make a gif, so it looks bumpy(sorry again): enter image description here




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...