【发布时间】:2015-07-03 04:30:40
【问题描述】:
我是编程新手,我正在构建一个简单的 pong 应用程序时遇到问题。这个想法是玩家 1 控制左侧和顶部桨,而玩家 2 控制右侧和底部。程序没有完成,但我遇到了问题。现在使用我的代码,桨要么根本不动,要么沿对角线移动,而不是从左到右移动两个桨。非常感谢您的帮助,任何有关如何修复或更好地组织我的程序的指示都将不胜感激。感谢您的时间和帮助。
package xpong;
import processing.core.PApplet;
import processing.core.PFont;
import processing.core.PImage;
public class XPong extends PApplet {
PFont f;
public boolean sideMoveLeft = false;
public boolean sideMoveRight = false;
public boolean topMoveLeft = false;
public boolean topMoveRight = false;
public float speed = 5;
public float x = 0;
public float y = 0;
public float a = 0;
public float b = 0;
public boolean sideMoving = false;
public boolean topMoving = false;
public void setup() {
size(800, 700);
background(255, 255, 255);
f = createFont("Arial",16,true);
smooth();
}
public void draw() {
background(255, 255, 255);
textFont(f,16);
fill(0);
text("Press Spacebar to Begin!",300, 350);
//leftBar();
//topBar();
//rightBar();
//bottomBar();
//Checks to see if if players keys are pressed to start playing and draws he bar
moveLeftAndRight();
translate(x, y);
leftBar();
rightBar();
/*if(key == 'q' || key == 'w'){
moveTopAndBottom();
translate(x, y);
topBar();
}*/
}
//Draws the bars
public void leftBar() {
fill(0, 0, 0);
rect(40, 260, 10, 200);
}
public void rightBar() {
fill(0, 0, 0);
rect(730, 260, 10, 200);
}
public void topBar() {
fill(0, 0, 0);
rect(300, 40, 200, 10);
}
public void bottomBar() {
fill(0, 0, 0);
rect(300, 650, 200, 10);
}
// Checks for key press and tells the program user wants to move
public void keyPressed(){
if(key == 'q')
{
sideMoveLeft = true;
topMoveLeft = true;
sideMoving = true;
topMoving = true;
}
if(key == 'w')
{
sideMoveRight = true;
topMoveRight = true;
sideMoving = true;
topMoving = true;
}
if(key == 'o'){
sideMoveLeft = true;
sideMoving = true;
}
if(key == 'p'){
sideMoveRight = true;
sideMoving = true;
}
}
//checks if the player has released the key to stop movement, and everything is set back to false
public void keyReleased(){
if(key == 'q')
{
sideMoveLeft = false;
topMoveLeft = false;
sideMoving = false;
topMoving = false;
}
if(key == 'w')
{
sideMoveRight = false;
topMoveRight = false;
sideMoving = false;
topMoving = false;
}
if(key == 'o'){
sideMoveLeft = false;
sideMoving = false;
}
if(key == 'p'){
sideMoveRight = false;
sideMoving = false;
}
}
//checks to see if users is pressing key and adds 5(speed) to y
public void moveLeftAndRight()
{
if(sideMoveRight)
{
y += speed;
}
if(sideMoveLeft)
{
y -= speed;
}
}
//checks to see if users is pressing key and adds 5(speed) to x
public void moveTopAndBottom()
{
if(topMoveRight)
{
x += speed;
}
if(topMoveLeft)
{
x -= speed;
}
}
}
【问题讨论】:
-
附带说明:您可能希望使用
keyPressed()来处理键盘输入。 -
好的,感谢您的快速和有用的输入。
-
如果我错了请纠正我,但默认情况下处理包括
update()方法。该方法在draw()之前调用,因此您可以将逻辑方法放在该块中,以使游戏更加流畅。 -
现在您检查两个不同位置的按键:
keyPressed()和draw()。这是一个坏主意。在绘图中,您不会对用户输入做出反应,您只会对您的文件(主要是布尔值)做出反应。你的面板还在对角线移动吗? -
是的,我试着看看我是否能让左右桨至少工作,但是说玩家 1 的键是 q 和 w,如果我按下它们,它会同时移动玩家 2 的桨时间不独立。我已经更新了代码。
标签: java processing