我正在使用javascript和processing.js處理簡單的pong副本。我已經制作了槳板的課程,然後將這些槳板擴展成一個由玩家控制的課程。目前,我正試圖在玩家控制的類中實現對鍵盤輸入的處理。我的意圖是,當按下w
或s
時,我通過玩家等級內的pVector
變量表示的速度更新玩家的槳的位置。使用velocity在javascript中使用processing.js移動矩形
然而,當按下相應的鍵時,槳現在簡單地消失。
該腳本可以看到的jsfiddle here,和我的代碼如下:
// For reference
// standard rectangle constructor is: rect(x, y, width, height);
class Paddle
{
//width of paddle
float pWidth;
//height of paddle
float pHeight;
//initial paddle x coordinate
float x;
//initial paddle y coordinate
float y;
Paddle(float w, float h, float startX, float startY)
{
//set width
paddleWidth = w;
//set height
paddleHeight = h;
//set start x
x = startX;
//set start y
y = startY;
}
void update()
{
}
void draw()
{
//draw and fill rectangle with white
fill(255)
rect(x,y,paddleWidth,paddleHeight)
}
}
class Player extends Paddle
{
Player(float w, float h, float startX, float startY)
{
super(w,h,startX,startY);
}
}
class PlayerOne extends Paddle
{
pVector playerVelocity = (0,0);
PlayerOne(float w, float h, float startX, float startY)
{
super(w,h,startX,startY);
}
void update()
{
debugger;
if(keyPressed)
{
if(key == 'w')
{
y -= playerVelocity.y;
}
else if(key == 's')
{
y += playerVelocity.y;
}
}
}
}
//array list to hold the player paddles
ArrayList<Paddle> paddles = new ArrayList<Paddle>();
//middle x and middle y
float mx, my, pw, ph;
void setup()
{
mx = width/2;
my = height/2;
pw = 10;
ph = 50;
player1 = new PlayerOne(pw,ph,10,10);
player2 = new Player(pw,ph,385,10);
paddles.add(player1);
paddles.add(player2);
size(400,400);
}
void draw()
{
background(0);
fill(100,100,0);
// update each paddle added to array list
for(Paddle p: paddles)
{
p.update();
p.draw();
}
}
我在做什麼錯?
UPDATE:
我把一個斷點與線debugger
上按鍵的條件後:if(keyPressed)
。看起來如果按鍵一次,出於某種原因每次更新都會重複檢測。
你嘗試使用JavaScript調試器?例如Firefox的Firebug插件。真正有用的解決這樣的問題。匆匆一瞥,你似乎並沒有處理出界的事情...... – Floris 2013-03-14 15:50:58
我真的一直在通過jsfiddle做所有的事情。瀏覽器js調試器是否允許調試通過jsfiddle運行的代碼?我的假設是肯定的,因爲我假設一個腳本是通過網站運行的,所以如果這是一個愚蠢的問題,請原諒我的無知。 – Christian 2013-03-14 15:53:30
沒關係,在鍵盤按下條件後,我可以在'debugger'這一行放置一個斷點:'if(keyPressed)'。看起來如果按鍵一次,出於某種原因每次更新都會重複檢測。 – Christian 2013-03-14 16:05:12