![](/img/trans.png)
[英]Android - buttons go off the edge of the screen, but text view fits in the screen
[英]Character falls off the edge of the screen
因此,我正在制作一个游戏,用户控制了一个矩形,该矩形沿着底部的框从左到右移动,但是它掉到了边缘,而且我不知道如何阻止这种情况,我们将不胜感激。 我已经尝试了很多方法来阻止这种情况,但是没有任何效果,我真的需要一些帮助才能将矩形实际显示在屏幕上。
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();
}
}}
我确实需要一些帮助,以将矩形实际保留在屏幕上。
好了,您需要做一些基本的逻辑检查,以查看矩形是否可以在面板的边界内绘制。
现在,您要确定矩形的位置和宽度,因此只需检查总和是否不大于面板的宽度即可。
例如,您可以检查“使用键盘运动”中的逻辑。 所有代码示例都包含move(...)
方法,该方法进行边界检查。
另外,从示例中注意,您的绘画代码不应用于计算字符的位置。 绘制方法应仅基于角色的当前属性来绘制角色。 只有用户操作才能更改角色的属性,因为您无法控制何时调用绘画方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.