p5.js – Create, Move and Interact with Sprites

 

Here are some additional exercises, they prepare you for the game we will do in the following lessons, step by step.

Create a smiley

181105 Smiley oho

Smiley with p5.js

As a first step only create the lower lip, then you have a “classical” smiley. You need – a circle for the head
– two ellipsoids for the eyes
– one arc for the mouth.
– You may also need to choose filling colours along the way, do it before you are drawing shapes.
– Then add another arc and colour the space in between upper and lower lip.

Create a Packman sprite

pacman-151558_640.png

Hint: There is a shape function “arc(…)” that allows you to create the body of the Packman with one line. Have a look in the documentation and play around with the parameters inside the parenthesis.

Don’t forget that angles are entered in radians. 0 degree is 0 radian, 180 degrees are PI radians and 360 degrees are 2*PI radians. PI is a constant in p5js, its actual value is 3.14… You only need to generate the Packman, the three small circles we do not need for now.

Control the movements of your sprite with the mouse

How to interact with your program? How can you control what is happening on the canvas?

P5JS gives you access to the mouse and the keyboard.

The mouseX and mouseY variables return you the current position of the mouse cursor. You can use it to make a rectangle follow your mouse on the canvas:

181106 mouseX.jpg

Here is a video p5js mouse position that shows you more about this mouse variables and some related variables.

Your program can also recognize when the mouse is pressed and then do something. Here is a code snippet, you add your action between the curly brackets.

A shorter way for the if statement is simply “if (mousePressed) { … .”

[code language="javascript"]

if (mouseIsPressed == true) {
// do something
}

[/code]

Control the movements of your sprite with the keyboard

You can also use the keyboard to control what is happening on the canvas. Here is a code snippet that uses four different keys. You find more information about the subject of keycodes in the reference documentation.

181106 p5js_KeyEvents.jpg

Make a rectangle change its colour depending on mouse or keyboard events

Now you have all the tools you need to create a small project that changes colour and or position of a rectangle. Here is a nice example

Next Step for the Packman game

With the examples given before, you can now make the Packman follow a horizontal line along the x axes.  The tricky part consists in making him turn and then also turning his face. Think about a solution before you have a look https://editor.p5js.org/mikefromd/embed/Skn51kA3m“>here and this is the code

Published by


Leave a Reply

Discover more from My WordPress Site

Subscribe now to keep reading and get access to the full archive.

Continue reading