//***************************Scene - Update Every Frame Event********************//
// get the position of the mouse pointer
var mousePosition = getPointerPos();

// check to see if the space bar is pressed 
var spaceIsPressed = isKeyPressed(Keys.space);

// if the space bar is pressed 
// and if the ball is not already launched 
if( spaceIsPressed && !ball.isLaunched ) {
    // update the message
    message.text("Launched!");
    
    // give the ball x and y velocities
    ball.velocityX = mousePosition.x - cannon.x();
    ball.velocityY = mousePosition.y - cannon.y();
    
    // launch the ball
    ball.isLaunched = true;
}

//*******************ball Object - Initialize When Scene Starts Event*************//
// track if the ball has been launched 
$this.isLaunched = false;

// reset the ball's position
// and set isLaunched to false
$this.resetBall = function() {
    $this.x(35);
    $this.y(550);
    $this.isLaunched = false;
};

//*******************ball Object - Update Every Frame Event***********************//
// if the ball is launched 
if ($this.isLaunched) {
    // move the ball based on its velocity
    $this.moveX($this.velocityX);
    $this.moveY($this.velocityY);
    
    // change the y velocity due to gravity
    $this.velocityY += 10;
    
    // if the ball goes off the screen
    if ($this.x() > 800 || $this.y() > 600) {
        //reset ball and update message
        $this.resetBall();
        message.text("Miss!");
    }
}

// if the ball touches the basket
if($this.isTouching(basket)) {
    $this.resetBall()
    message.text("Score!")
}

//********************basket Group - Update Every Frame Event*********************//
// move the basket group
$this.moveY();

// if it reaches the top
if($this.y() < 100) {
    $this.speedY(50);
}

// if it reaches the bottom
if($this.y() > 500) {
    $this.speedY(-50);
}

//********************cannon Object - Update Evey Frame Event*********************//
// point the cannon to the cursor
$this.pointToCursor();
