Question: this is a javascript ping pong game. i need to get the left paddle to move with keys w and s. the right paddle needs
this is a javascript ping pong game. i need to get the left paddle to move with keys w and s. the right paddle needs to move with up and down arrow key. how do i do this, please use the code i already have and add on please
To play the game, move the keys W or S to move up or down
for the left paddle. To move the right paddle, simply move the up
or down arrow keys
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
height: 600px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
var canvas, paddle1, paddle2, ctx;
/* set the canvas size and color */
var canvas = document.getElementById("myCanvas");
canvas.addEventListener('keydown', moveIt, true);
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fill();
var x = canvas.width;
var y = canvas.height;
var dx = 2;
var dy = -2;
ctx.beginPath();
ctx.rect(20, 20, 800, 800);
ctx.fill();
/* dimensions of the ball */
var xposball = 200;
var yposball = 300;
/* radius of the ball */
var radiusball = 12;
/* speed of the ball */
var xspeedball = 1;
var yspeedball = 1;
/* direction of the ball */
xdirball = 0.8;
ydirball = 0.8;
/* speed of the game */
var gamespeed = 2;
/* add the ball, paddles, and canvas to game */
function draw(){
ctx.fillStyle = "green";
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fill();
// paddle 1
paddle1 = ctx.rect(18, 115, 20, 150);
ctx.fillStyle = 'black';
ctx.stroke();
// paddle 2
paddle2 = ctx.rect(763, 115, 20, 150);
ctx.fillStyle = 'black';
ctx.fill();
ctx.stroke();
/* draw the ball */
ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(xposball, yposball, radiusball, 0, 2 * Math.PI, false);
ctx.fill();
ctx.closePath();
// moving the ball
xposball = xposball + xspeedball * xdirball;
yposball = yposball + yspeedball * ydirball;
// setting out of bounds for the top and bottom of the
// canvas
if ((xposball > (canvas.width - radiusball)) || ((xposball - radiusball) < 0)) {
xdirball = -1 * xdirball;
}
xposball = xposball + xspeedball * xdirball;
if ((yposball > (canvas.height - radiusball)) || ((yposball - radiusball) < 0)) {
ydirball = -1 * ydirball;
}
yposball = yposball + yspeedball * ydirball;
}
function moveIt(e){
if(e.keyCode == 38)
{
ctx.clearRect(0,0, canvas.width, canvas.height);
y = y-10;
ctx.fillRect(18, 115, 20, 150);
}
}
// calling our draw function, and game speed
setInterval(draw, gamespeed);
moveIt(e);
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
