Moving graphics with arrow keys simple problem
Hey everyone, firstly I'd just like to say that I'm new to the site :)
Secondly, I have a problem that I just can't solve myself.
So I'm making a program for air hockey, and I'm moving blue Ellipse2D Shape object (circle) with my arrow keys (Up, left, down, right).
The problem is, is that when I press for example the up key I don't want the circle to leave the frame. Now see I tried putting if statements, while loops, and nothing goes well. No matter what if as long as I HOLD my keys, they could surpass the frame boundaries.
Code:
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.util.*;
import java.util.*;
import java.awt.event.*;
import java.awt.geom.*;
public class AirHockey extends JPanel implements ActionListener, KeyListener{
double x, y;
double velX = 0, velY = 0;
public AirHockey() {
Timer t = new Timer(5, this);
t.start();
addKeyListener(this);
setFocusable(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Shape circle = new Ellipse2D.Double(x, y, 40, 40);
g2.setColor(Color.BLUE);
g2.fill(circle);
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
x += velX;
y += velY;
}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
velY = -2;
velX = 0;
}
if (code == KeyEvent.VK_DOWN) {
velY = 2;
velX = 0;
}
if (code == KeyEvent.VK_LEFT) {
if (x < 0) {
velY = 0;
velX = 0;
}else {
velY = 0;
velX = -2;
}
}
if (code == KeyEvent.VK_RIGHT) {
if (x > 760) {
velY = 0;
velX = 0;
}
velY = 0;
velX = 2;
}
}
@Override
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
velY = 0;
velX = 0;
}
if (code == KeyEvent.VK_DOWN) {
velY = 0;
velX = 0;
}
if (code == KeyEvent.VK_LEFT) {
velY = 0;
velX = 0;
}
if (code == KeyEvent.VK_RIGHT) {
velY = 0;
velX = 0;
}
}
@Override
public void keyTyped(KeyEvent e) {
}
}
Re: Moving graphics with arrow keys simple problem
I don't see any if statements regarding boundaries in the current code that you've posted. Why not show us your attempt at using these.
Re: Moving graphics with arrow keys simple problem
There are attempts in the code I posted right now, look at the keyPressed method there are some if statements I tried for a few of them.
Re: Moving graphics with arrow keys simple problem
The code looks reasonable for the left/right keys. You need to add some debug code to see what the actual value of x/y are when the KeyEvents are when the KeyEvents are generated and when the Timer fires.
Re: Moving graphics with arrow keys simple problem
I found a fix guys. I made it so that when the Ellipse2D object hit the edge of the screen, it kept the x or y coordinate stationary so it would never change. Yayy... :)