gpt4 book ai didi

java - 我可以使用循环来同时水平和垂直移动吗?

转载 作者:行者123 更新时间:2023-12-01 12:58:48 25 4
gpt4 key购买 nike

我正在制作这个简单的游戏(只是为了好玩),当我说简单时,我真的希望它简单。现在到目前为止我已经有了一个可以移动到任何我想要的地方的正方形。我正在使用 KeyListeners(工作完全正常,我不想在当前项目中使用 KeyBindings),我想知道是否可以使用循环来使其同时水平和垂直移动。在此代码中,您可以见证我尝试放入循环,它在 while 下给了我一个错误:

Syntax error on token while

我有两个问题1.循环能完成我想要的事情吗? 如果不是,你有什么建议?2. 如果是,我的 while 循环有什么问题?

谢谢

我的代码:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx =0, vely =0, loop = 0;

public MyGame() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x,y,50,30);
}

public void actionPerformed(ActionEvent e) {
if(x < 0)
{
velx=0;
x = 0;
}

if(x > 530)
{
velx=0;
x = 530;
}

if(y < 0)
{
vely=0;
y = 0;
}

if(y > 330)
{
vely=0;
y = 330;
}

x += velx;
y += vely;
repaint();
}
while (loop = 0) {
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();

if (code == KeyEvent.VK_DOWN){
vely = 1;
velx = 0;
}
if (code == KeyEvent.VK_UP){
vely = -1;
velx = 0;
}
if (code == KeyEvent.VK_LEFT){
vely = 0;
velx = -1;
}
if (code == KeyEvent.VK_RIGHT){
vely = 0;
velx = 1;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
velx=0;
vely=0;
}}


public static void main (String arge[]){

JFrame f = new JFrame();
MyGame s = new MyGame();
f.add(s);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600,400);
f.setVisible(true);

}
}

最佳答案

首先,您不能在方法之外声明循环。要解决您的问题,您应该删除循环并更改您的 vely/velx 分配。要同时注册多个键,您应该只将一个变量设置为 1 或 -1,而保留另一个变量。

if (code == KeyEvent.VK_DOWN){
vely = 1;
}

现在,由于您要注册多个键,您还必须在 keyreleased 方法中区分它们,您现在应该将适当的速度设置为 0 并让另一个保持不变。

关于java - 我可以使用循环来同时水平和垂直移动吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23666738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com