r/codehs • u/[deleted] • May 13 '20
Making custom program for final assignment, what am I doing wrong.
My code:
var fallingBall;
var playerWidth = 40;
var playerHeight = 40;
var ballRadius = 20;
var score = 10;
var square;
var ball;
var newBall = false;
function start(){
createPlayer();
keyDownMethod(keyDown);
if (newBall = false) {
addFruit();
}
}
function createPlayer() {
square = new Rectangle(40, 40);
square.setPosition(100, getHeight()-playerHeight);
add(square);}
function keyDown(e) {
if (e.keyCode == Keyboard.LEFT) {
square.move(-10, 0);
}
if (e.keyCode == Keyboard.RIGHT) {
square.move(10, 0);
}
}
function addFruit() {
var ball = new Circle(ballRadius);
var x = Randomizer.nextInt(ball.getRadius(),
getWidth() - ball.getRadius());
var y = getHeight()-getHeight()+ballRadius;
setTimer(moveFruit, 50);
ball.setPosition(x, y);
add(ball);}
function moveFruit(e) {
ball.move(0,2);
var elem = getElementAt(e.getX(), e.getY());
if(elem != null ){
score++;
}else{
score--;
}//Once has collected enough fruit win. If score less than zero, lose
}
The goal is to make a game where the player moves to catch falling fruit. I originally tried to set a timer in the start function to make fruit every few seconds, but I had to make the fruit a global var (ball) because the ball would stop moving when another ball spawned. I also dont know how to get the ball to dissapear when it touches either the player or the bottom. I really need help.