PICO-8
Ball Bouncing Tutorial

Step 0: Draw your Ball

First things first. Start PICO-8, press the Escape Key, and go to the Draw tab. Now you can draw your ball in Sprite Slot 001.

Step 1: Draw the Ball

Now lets draw the ball to the screen. Go to the code tab and enter this code.


-- ball properties
ball_x = 0  -- x position
ball_y = 0  -- y position

-- draw function
function _draw()
  -- clear the screen
  cls()
  
  -- draw the ball
  spr(1, ball_x, ball_y)
end
        

To Run the code press [ CTRL ] + [ R ]. Now the ball will be drawn in the top left corner of the screen.

Step 2: Move the Ball to the Right

Next, we'll make the ball move to the right.


-- ball properties
ball_x = 0  -- x position
ball_y = 0  -- y position

-- update function
function _update()
  -- move the ball right
  ball_x = ball_x + 1
end

-- draw function
function _draw()
  -- clear the screen
  cls()
  
  -- draw the ball
  spr(1, ball_x, ball_y)
end
        

Now the ball moves to the right... forever.

Step 3: Make the Ball Bounce Back

Next, we add speed to the ball and collision detection to make the ball bounce back when it hits the left or right edge of the screen.


-- ball properties
ball_x = 0  -- x position
ball_y = 0  -- y position
speed = 2   -- speed

-- update function
function _update()
  -- update ball position
  ball_x = ball_x + speed
  
  -- when ball hits sides
  if ball_x < 0 or ball_x > 119 then
    -- reverse the direction
    speed = speed * -1
  end
end

-- draw function
function _draw()
  -- clear the screen
  cls()
  
  -- draw the ball
  spr(1, ball_x, ball_y)
end
        

Now the ball bounces off the left and right sides of the screen and moves faster.

Step 4: Add Up and Down Bouncing

Lets add in vertical some speed.


-- ball properties
ball_x = 0  -- x position
ball_y = 0  -- y position
x_speed = 2   -- x speed
y_speed = 1.5 -- y speed

-- update function
function _update()
  -- update ball position
  ball_x = ball_x + x_speed
  ball_y = ball_y + y_speed
  
  -- left or right side
  if ball_x < 0 or ball_x > 119 then
    -- reverse x direction
    x_speed = x_speed * -1
  end
  
  -- top or bottom side
  if ball_y < 0 or ball_y > 119 then
    -- reverse y direction
    y_speed = y_speed * -1
  end
end

-- draw function
function _draw()
  -- clear the screen
  cls()
  
  -- draw the ball
  spr(1, ball_x, ball_y)
end
        

Now the ball can move in both directions and bouncing off all four edges of the screen! Great job!

Summary

Now you have learned to draw a Sprite to the screen and make it move around. Next we will add a player!


Next Tutorial ➡