所以基本上我只是为了不同的目的玩弄运动系统,很难让正方形停在边缘。正方形从屏幕一侧移动了大约50%的正方形,我不明白为什么会这样。
package SnakeMovement;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class SnakeMovement extends Canvas implements ActionListener, KeyListener {
Timer timer = new Timer(5, this);
int width, height;
int xSize = 50, ySize = 50;
int yPos = 0, xPos = 0, yVel = 0, xVel = 0;
public SnakeMovement(int w, int h) {
timer.start();
width = w;
height = h;
addKeyListener(this);
setFocusTraversalKeysEnabled(false);
setFocusable(true);
}
public void paint(Graphics g) {
super.paint(g);
g.fillRect(xPos, yPos, xSize, ySize);
}
public void actionPerformed(ActionEvent e) {
xPos += xVel;
yPos += yVel;
if (xPos >= width - xSize) {
xPos = width - xSize;
xVel = 0;
}
repaint();
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
yVel = -10;
xVel = 0;
}
if (key == KeyEvent.VK_S) {
yVel = 10;
xVel = 0;
}
if (key == KeyEvent.VK_A) {
xVel = -10;
yVel = 0;
}
if (key == KeyEvent.VK_D) {
xVel = 10;
yVel = 0;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
我只想在屏幕的每一边都有一个正方形的站在边缘。
1条答案
按热度按时间v2g6jxz61#
尝试:
其思想是使用边框颜色绘制一个全尺寸的矩形。
然后用长方形的颜色画一个小的(2*border\u大小)。
以下是上述的mre: