2016-07-26 2 views
0

Я работаю над игрой в плей-офф 2 игрока, и я использую ключи W, D, S, A для второго игрока. Он работает, но направление весла 2-го игрока удваивается.JS keydown не работает

Если вы не понимаете, см. Это Demo. Я попытался перерисовать весло после нажатия клавиши, но ничего не сделал.

JS

/* VARIABLES */ 

//Canvas and context 
var canvas, ctx; 

//Balls x and y 
var ballX, ballY; 
var ballSpeedX, ballSpeedY; //Balls x and y speed 

//Player1 x, y 
var player1X, player1Y; 

//Player2 x, y 
var player2X, player2Y; 

var playerSpeedY; //Players speed 

//Players w and h 
const PLAYER_WIDTH = 10; 
const PLAYER_HEIGHT = 100; 

const WIN_SCORE = 3; //Max score 

/* FUNCTIONS */ 

//Draw stuff 
function draw() { 

    //Clear canvas 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 

    //Draw player 1 
    drawPlayer1(player1X, player1Y, PLAYER_WIDTH, PLAYER_HEIGHT, "white"); 

    //Draw player 2 
    drawPlayer2(player2X, player2Y, PLAYER_WIDTH, PLAYER_HEIGHT, "white"); 

    //Draw ball 
    drawBall(ballX, ballY, 10, "white"); 

    //Draw score board 

} 

//Animate stuff 
function animate() { 

    ballX += ballSpeedX; 
    ballY += ballSpeedY; 

} 

//Detect collisiom 
function collision() { 

    //If ball hits x and y walls 
    //X walls 
    if (ballX >= canvas.width) { //Right wall 

     ballSpeedX = -ballSpeedX; 

    } 
    if (ballX <= 0) { //:Left wall 

     ballSpeedX = -ballSpeedX; 

    } 

    //Y walls 
    if (ballY >= canvas.height) { //Bottom wall 

     ballSpeedY = -ballSpeedY; 

    } 
    if (ballY <= 0) { //Top wall 

     ballSpeedY = -ballSpeedY; 

    } 

} 

//Reset ball 
function resetBall() {} 

//Player 1's control (W, S, D, A) 
function player1Control(e) {} 

//Player 2's control (Arrow keys) 
function player2Control(e) { 

    if (e.keyCode == "40") { 

     player2Y += 0.2; 
     drawPlayer2(player2X, player2Y, PLAYER_WIDTH, PLAYER_HEIGHT, "white"); 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 

    } 

    if (e.keyCode == "38") { 

     player2Y -= 0.2; 
     drawPlayer2(player2X, player2Y, PLAYER_WIDTH, PLAYER_HEIGHT, "white"); 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 

    } 

} 

//Detect if a player gets up to max score 
function scoreCheck() {} 

/* OBJECT FUNCTIONS */ 

//Draw ball 
function drawBall(x, y, r, color) { 

    ctx.fillStyle = color; 
    ctx.beginPath(); 
    ctx.arc(x, y, r, 0, Math.PI * 2); 
    ctx.fill(); 

} 

//Draw player 1's paddle 
function drawPlayer1(x, y, w, h, color) { 

    ctx.fillStyle = color; 
    ctx.fillRect(x, y, w, h); 

} 

//Draw player 2's paddle 
function drawPlayer2(x, y, w, h, color) { 

    ctx.fillStyle = color; 
    ctx.fillRect(x, y, w, h); 

} 

//Draw score board 
function drawScore(x, y, text, font, color) {} 

/* WHEN DOCUMENT IS READY */ 
$(document).ready(function() { 

    //Call canvas 
    canvas = $("#canvas")[0]; 
    //Get context 
    ctx = canvas.getContext("2d"); 

    //Set values to object variables 
    //ball x and y 
    ballX = 200; 
    ballY = 200; 
    ballSpeedX = 2; 
    ballSpeedY = 2; 

    //Player 1 
    player1X = 0; 
    player1Y = canvas.height/2 - PLAYER_HEIGHT/2; 

    player2X = canvas.width - PLAYER_WIDTH; 
    player2Y = canvas.height/2 - PLAYER_HEIGHT/2; 

    playerSpeedY = 2; 

    var fps = 60; 
    setInterval(function() { 

     draw(); 
     animate(); 
     collision(); 

     $(window).bind("keydown", player1Control); 
     $(window).bind("keydown", player2Control); 

    }, fps/1000); 

}); 

HTML

<!DOCTYPE html> 
<html> 

<head> 
    <title>Pong - 2 Player</title> 

    <link rel="stylesheet" href="style.css"> 
</head> 

<body> 
    <center> 
     <canvas id="canvas" width="800" height="600" style="background-color: #000"></canvas> 
    </center> 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
    <script src="main.JS"></script> 
</body> 

</html> 

ответ

2

Вы добавляете слушатель событий внутри setInterval

setInterval(function() { 

    draw(); 
    animate(); 
    collision(); 

    $(window).bind("keydown", player1Control); 
    $(window).bind("keydown", player2Control); 

}, fps/1000); 

так каждый раз, когда интервал проходит событие регистрируется вновь. Это приводит к тому, что player1Control и player2Control работают несколько раз.

Просто переместите эти две строки из интервала

setInterval(function() { 

    draw(); 
    animate(); 
    collision(); 

}, fps/1000); 
$(window).bind("keydown", player1Control); 
$(window).bind("keydown", player2Control); 
+0

Благодаря коды работали –

Смежные вопросы