Step 1: Create an Index.html file
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>
<script src ="player.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>
Create a canvas and show a black background
Create global variable called var p to store a player instance
Create a new player instance using the global p variable
var p; // global variable for player
function setup() {
createCanvas(640, 360); // set canvas size
p = new player();
}
function draw() {
background(0); //draw background black
}
Create a new class and properties.
Create a move() function to move sprite with keyboard keys.
Create a display function to update sprite location and draw
class player {
constructor() {
this.x = random(width);
this.y = random(height);
this.diameter = 30;
this.speed = 10;
}
//basic player movement it will move continuously in that direction
move() {
if (keyIsDown(RIGHT_ARROW) && this.x < width - this.diameter) {
this.x += this.speed; //, this.speed;
}
if (keyIsDown(LEFT_ARROW) && this.x > 0) {
this.x -= this.speed; //, this.speed;
}
if (keyIsDown(UP_ARROW) && this.y > 0) {
this.y -= this.speed; //, this.speed;
}
if (keyIsDown(DOWN_ARROW) && this.y < height - this.diameter) {
this.y += this.speed; //, this.speed;
}
}
//update and display the player
display() {
fill(255, 204, 0);
rect(this.x, this.y, this.diameter, this.diameter);
}
}
add the move() and display() function to the draw() function. Make sure you reference the newly created player class with p (variable)
var p; //this will store the properties for player
function setup() {
createCanvas(640, 360); // set canvas size
p = new player();
}
function draw() {
background(0); //drawbackground black
p.display();
p.move();
}