我正在開發一個處理(在Java上運行)的雙人遊戲。一個用戶將使用WASD鍵控制他的角色,另一個用戶使用箭頭鍵控制移動。我遇到的問題是使用keyPressed
時,按下箭頭時將WASD取消,反之亦然。我一直在搞這件事很長時間。有沒有人知道一個工作或注意到我做錯了什麼?同時使用WASD和箭頭鍵
//global variables
int wide = 600; //canvas width
int tall = 600; //canvas height
int s = 50; //player size
float speed = 2.5; //player movement speed
//colors
int redColor = #CB4646; //player 1 color
int blueColor = #4652CB; //player 2 color
int backgroundColor = #DBE3B3; //background color
float player1X = 600/3-s; //HOW COME width/3 DOESN'T WORK??????????
float player2X = 600*2/3;
float playerY = 600/2-(s/2);
//players
Player player1 = new Player(player1X, playerY, s, speed, "wasd", redColor); //player 1
Player player2 = new Player(player2X, playerY, s, speed, "arrows", blueColor); //player 2
//setup
void setup(){
background(backgroundColor);
size(wide, tall);
smooth();
println(player2.controls);
}
//draw
void draw(){
background(backgroundColor);
player1.usePlayer();
player2.usePlayer();
}
class Player{
//class variables
float x; // x position
float y; // y position
int s; //size
float speed; //speed
String controls; //controls
int colors; //player color
char keyControls [] = new char [4];
//construct
Player(float tempX, float tempY, int tempS , float tempSpeed, String tempControls, int tempColors){
x = tempX;
y = tempY;
s = tempS;
speed = tempSpeed;
controls = tempControls;
colors = tempColors;
}
void usePlayer(){
// draw player
fill(colors);
rect(x, y, s, s);
//move player
keyPressed();
//wraparound
boundaries();
}
void keyPressed(){
//sets controls for wasd
if(controls == "wasd"){
if(key == 'w' || key == 'W'){
y -= speed; //move forwards
}
if(key == 's' || key == 'S'){
y += speed; //move backwards
}
if(key == 'd' || key == 'D'){
x += speed; //move right
}
if(key == 'a' || key == 'A'){
x -= speed; //move left
}
}
//sets controls for arrows
if(controls == "arrows"){
if(key == CODED){
if(keyCode == UP){
y -= speed; //move forwards
}
if(keyCode == DOWN){
y += speed; //move backwards
}
if(keyCode == RIGHT){
x += speed; //move right
}
if(keyCode == LEFT){
x -= speed; //move left
}
}
}
}
//pacman style wraparound
void boundaries(){
if(x == width) x = 2;
if(y == height) y = 2;
if(x == 0) x = width-s;
if(y == 0) y = height-s;
}
}
是否與鍵盤無法一次註冊超過2-6個鍵(取決於哪個鍵)相關? – Patashu 2013-02-12 03:17:09
@Patashu,我不這麼認爲,因爲當我同時按下兩個按鈕時它不起作用。 – Brannon 2013-02-12 04:58:29
請注意,這實際上不是一個Java問題,而是一個Processing問題。 Processing是一個非常具體的API,它的程序設計模型與Java稍有不同(它被重寫爲Java,以便在JVM中脫機使用,但在瀏覽器中在線使用時會重寫爲JavaScript) – 2013-02-12 15:35:52