I have been learning javascript for a few days and have been practising on a bouncing ball game. Anyway, I am trying to get html user input to change the speed of the ball, but it does not seem to work. I created a doStuff function to grab the html userinput value and tried to set this to the ball speed, but it does not change the initial speed that I gave it. Can someone show me what I did wrong in the code? Thanks
Blockquote
// declare variables
const FPS = 60;
var bs = 30;
var bx, by;
var xv, yv;
var canvas, context;
var bsp = 400;
// load canvas
canvas = document.getElementById("gameCanvas");
context = canvas.getContext("2d");
// set up interval (game loop)
setInterval(update, 1000 / FPS);
function doStuff() {
var nameElement = document.getElementById("someInput");
// ball speed
bsp = nameElement.value;
}
// ball starting position
bx = canvas.width / 2;
by = canvas.height / 2;
// random ball starting speed (between 10 and 60 pps)
xv = Math.floor(Math.random() * 10 + bsp) / FPS;
yv = Math.floor(Math.random() * 10 + bsp) / FPS;
// random ball direction
if (Math.floor(Math.random() * 2) == 0) {
xv = -xv;
}
if (Math.floor(Math.random() * 2) == 0) {
yv = -yv;
}
// update function
function update() {
// move the ball
bx += xv;
by += yv;
// bounce the ball off each wall
if (bx - bs / 2 < 0 && xv < 0) {
xv = -xv;
}
if (bx + bs / 2 > canvas.width && xv > 0) {
xv = -xv;
}
if (by - bs / 2 < 0 && yv < 0) {
yv = -yv;
}
if (by + bs / 2 > canvas.height && yv > 0) {
yv = -yv;
}
// draw background and ball
context.fillStyle = "white";
context.fillRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.fillStyle = "#CCCC00";
context.arc(bx, by, bs, 0, Math.PI * 2, true);
context.fillStyle = "#000000";
context.closePath();
context.fill();
}
> Blockquote
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ball</title>
<body>
<head>
<title>Ball Speed</title>
</head>
<h1>Ball Speed</h1>
<body>
<br>
<input id="someInput" type="number">
<input type="button" value="Sumbit" onClick="doStuff()">
</body>
<canvas id="gameCanvas" width="1900" height="750"></canvas>
</html>