Lesson 3.3

Logical Operators

Watch: Else and Else if, AND and OR - p5.js Tutorial

Video for 3.3:

With logical operators we can write more complex conditional expressions.

For example, if you wanted to change the speed of a ball to –speed either when ball.x > 390 or ball.x < 10, there are two ways to write it.The first way involves two independent statements.

The first way involves two independent statements.

We can more efficiently combine these by using the logical operator or which is written as ||.

If we want two or more conditions to be met in order to run a block of code we use the logical operator and which is written as &&. The following checks if ball.x is between 10 and 100.

You can also combine expressions. The following checks if a ball is either on the left or right side of the canvas.

Exercise 3.3a: Make a simple pong game. Have two rectangular paddles move up and down with the mouse. If the ball hits the paddle it bounces off, if it does not, the game is over. To provide more challenge, increase the speed of the ball with each mouse click.

Exercise 3.3a

Exercise 3.3a help