I simply cannot wrap my head around how to import a library into my project. I'm trying to add p5.js to my project because I'd like to use their KeyisPressed variable for player movement. But I cannot figure out what I'm doing wrong here... I'm probably missing something incredibly obvious but I cannot for the life of me figure out what it is and I need help.
Forgot to add this: Player.js:84 Uncaught ReferenceError: keyIsPressed is not defined
at Player.update (Player.js:84:9) EDIT: After having messed around just slightly with the code and linking 'keyIsPressed' to 'context' (which is my canvas) I've gotten a new error.
Uncaught TypeError: Cannot read properties of undefined (reading 'keyIsPressed') at Player.update (Player.js:85:21)
which leads me to believe that perhaps my p5.js isn't being initialised correctly?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<meta name="description" content="">
<meta name="author" content="">
<script src="p5/p5.js"></script>
<script type="text/javascript" src="GameWorld.js"></script>
<script type="text/javascript" src="GameObject.js"></script>
<script src="Player.js"></script>
<script type="text/javascript" src="Square.js"></script>
</head>
<body>
<canvas id="canvas" width="750" height="400" style="border:1px solid lightgrey;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
// Listen to the onLoad event, then create a game world
window.onload = function (){
let gameWorld = new GameWorld('canvas');
}
</script>
</body>
</html>
Player.js (which is where I'm trying to use this function)
var keyW;
var keyA;
var keyD;
var context;
class Player extends GameObject
{
static sprite;
constructor(context, x, y, vx, vy)
{
super(context, x, y, vx, vy);
this.loadImage();
}
loadImage()
{
// Check for an existing image
if (!Player.sprite)
{
// No image found, create a new element
Player.sprite = new Image();
// Handle a successful load
Player.sprite.onload = () =>
{
// Define the size of a frame
Player.frameWidth = Player.sprite.width;
Player.frameHeight = Player.sprite.height;
this.height = Player.sprite.height;
this.width = Player.sprite.width;
};
// Start loading the image
Player.sprite.src = 'images/jetpack_man_left.png';
}
}
draw()
{
// Draw the image
this.context.drawImage(Player.sprite, this.x, this.y);
}
update(secondsPassed)
{
if (context.keyIsPressed === true)
{
switch (key)
{
case 'W':
case 'w':
y++;
break;
case 'A':
case 'a':
x--;
break;
case 'D':
case 'd':
x++;
break;
}
}
}
}