Question
using my javascript code, i need to be able to move my paddles up and down. this is a ping pong game. use key w
using my javascript code, i need to be able to move my paddles up and down. this is a ping pong game. use key w and s to move left paddle, and the up and down arrow key to move the right paddle. Please use the code I already have below and add on, thanks
var canvas, paddle1, paddle2, ctx;
/* set the canvas size and color */
var canvas = document.getElementById("myCanvas");
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 = 1;
ydirball = 1;
/* 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.fill();
// paddle 1
ctx.rect(39, 115, 20, 150);
ctx.fillStyle = 'black';
ctx.stroke();
// paddle 2
ctx.rect(770, 115, 20, 150);
ctx.fillStyle = 'black';
ctx.stroke();
/* draw the ball */
ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(xposball, yposball, radiusball, 0, 2 * Math.PI, false);
ctx.fill();
ctx.closePath();
xposball = xposball + xspeedball * xdirball;
yposball = yposball + yspeedball * ydirball;
}
// calling our draw function, and game speed
setInterval(draw, gamespeed);
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started