所以我正在制作一个游戏,用户控制一个矩形,从底部的一个盒子左右移动,但它落在边缘,我不知道如何阻止这个,帮助将不胜感激。我已经尝试了很多东西来阻止它,但没有任何效果,我真的需要一些帮助来保持矩形实际上在屏幕上。
public Rectangle character;
public Rectangle bottomBox;
public int charW = 100;
public int charH = 15;
public boolean right = false;
public boolean left = false;
public boolean up = false;
public boolean down = false;
public boolean mouseActive = false;
public Point mouse;
public Keying(Display f, Images i){
character = new Rectangle(180, 180, charW, charH);
bottomBox = new Rectangle (0, 350, 9000, 30);
f.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
mouseActive = false;
right = true;
character.x += 1;
}
if(e.getKeyCode() == KeyEvent.VK_A){
mouseActive = false;
left = true;
character.x -= 1;
}
if(e.getKeyCode() == KeyEvent.VK_M){
mouseActive = false;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_A){
left = false;
}
}
});
f.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e){
int mouseX = e.getX();
int mouseY = e.getY();
mouse = new Point(mouseX, mouseY);
if(mouseActive && character.x != Main.w - charW){
character.x = mouse.x;
character.y = mouse.y;
}
repaint();
}
});
f.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
mouse = new Point (e.getX(), e.getY());
if(e.getButton() == MouseEvent.NOBUTTON){
character.x = mouse.x;
character.y = mouse.y;
}
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Point pt1 = new Point(character.x, character.y + character.height);
if(!bottomBox.contains(pt1) && !mouseActive){
character.y++;
}
this.setBackground(Color.YELLOW);
{g.setColor(Color.BLACK);
g.fillRect(character.x, character.y, character.width, character.height);}
{g.setColor(Color.darkGray);
g.fillRect(bottomBox.x, bottomBox.y, bottomBox.width, bottomBox.height);
if(right && character.x != Main.w - charW){
character.x += 1;
}
if(left && character.x != 0){
character.x -= 1;
}
repaint();
}
} }
答案 0 :(得分:0)
我真的需要一些帮助才能将矩形实际保留在屏幕上。
你需要做一些基本的逻辑检查,看看是否可以在面板的范围内绘制矩形。
您现在可以看到矩形的位置和宽度,只需检查总和是否不大于面板的宽度。
例如,您可以查看Motion Using the Keyboard中找到的逻辑。所有代码示例都包含一个#include <type_traits>
template<typename T>
class Foo
{
static_assert(
std::is_base_of<MyBase, T>::value,
"T must be a descendant of MyBase"
);
void SomeMethod()
{
auto bar = T();
//or
auto bar = T("Constructor with parameter")
bar.someFunctionOnMyBase();
}
};
方法,用于进行边界检查。
另外,请注意示例中您的绘图代码不应计算字符的位置。绘制方法应该只根据角色的当前属性绘制角色。只有用户操作才能更改角色的属性,因为您无法控制何时调用绘制方法。