so basically when i use my arrow keys this red ball will move, but I can move it off the screen. How could I make it so that the ball wouldn't be able to move pass the border?
I was thinking about doing something like detecting if the position of the ball was >= the edge of the screen then it would respawn at like the middle, but wasn't sure how I should implement it.
//Name: anon Date:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
private class Key extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_UP) //arrow key
pd.setY( pd.getY()-10);
if(e.getKeyCode() == KeyEvent.VK_DOWN)
pd.setY( pd.getY()+10);
if(e.getKeyCode() == KeyEvent.VK_LEFT)
pd.setX( pd.getX()-10);
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
pd.setX( pd.getX()+10);
}
}
How about checking if the x coordinate plus the radius of the circle is out of bounds and then do the same for the y coordinate?
Point circleCenter;
int radius;
int screenW;
int screenH;
if (circleCenter.x + radius > screenW)
circleCenter.x = screenW - radius;
if (circleCenter.x - radius < 0)
circleCenter.x = 0 + radius;
if (circleCenter.y + radius > screenH)
circleCenter.y = screenH - radius;
if (circleCenter.y - radius < 0)
circleCenter.y = 0 + radius;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.