Closed davidnierman closed 2 years ago
found a work around by creating a global list of foods[] and pushing the object to the global list and then referencing the list element during the game loop
// create a function that creates food
const createFood = () => {
let foodX = 100;
let foodY = 222;
let foodWidth = 10;
let foodHeight = 10;
let food = new interactiveElement(foodX,foodY,foodWidth,foodHeight,"red")
console.log('this is the food instance ', food)
foods.push(food)
console.log('list of foods', foods)
}
// create a function that refreshes the page every 50 milliseconds to reflect the movements on the screen
const screenRefresh = () => {
console.log('screen refreshed!')
ctx.clearRect(0,0,500,500)
caterpillar.increaseSleepPoints()
bed.render()
caterpillar.render()
console.log('this is the food object,', foods[0])
foods[0].render()
}
I am leaving this open, because something is telling me this might not be the best way to solve this issue.
This is the way! Good job figuring it out, and thank you for a well constructed issue.
What's the problem you're trying to solve?
I am trying to create an instance of my class 'interactiveElement' and add it to my canvas
Post any code you think might be relevant (one fenced block per file)
If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?
error message:
main.js:107 Uncaught ReferenceError: food is not defined at screenRefresh (main.js:107:5)
What is your best guess as to the source of the problem?
I think it has to do with creating a local instance that cannot be accessed by the screenRefresh()
What things have you already tried to solve the problem?
To help pinpoint the issue I moved the following line out of the function (and replaced the variables with numbers) and put it next to the other instance creations and it worked.
js let food = new interactiveElement(foodX,foodY,foodWidth,foodHeight,"red")
so.. it seems nothing is wrong with creating the instance, but there is something wrong with referencing it each time the gameLoops (aka screenRefresh)?
I tried calling the function
createFood()
in different places i.e. during content load and then putting it under where the other two instances are created without using a function, but did not work...I have tried using a
return
statement, but not really sure how that is going to help here.. shot in the dark..I thought of ways that I might need to append it or something to the canvas, but that should be done when I create a new instance...
I tried using console.log to get a better idea of what is happening and it is calling the function and creating the object. So everything seems good until the gameloop happens then the object cannot be accessed or disappears or something..
Paste a link to your repository here
https://github.com/dnierman0920/game-project-Caterpillar