sei-ec-remote / project-1-issues

Open new issues here
1 stars 2 forks source link

instance of a class created in a function cannot be referenced during game loop aka screen refresh #14

Closed davidnierman closed 2 years ago

davidnierman commented 2 years ago

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)

//create a class that will be used to create interactive elements on the screen
class interactiveElement {
    constructor(x,y,width,height,color, opacity=1) {
        this.x = x,
        this.y = y,
        this.width = width,
        this.height = height,
        this.color = color,
        this.opacity = opacity,
        this.render = function() {
            ctx.fillStyle = this.color // change this later to an image instead of a color
            ctx.fillRect(this.x, this.y,this.width, this.height)
            ctx.localAlpha = this.opacity; // --> there is an issue here with opacity
            // ctx.fillRect will draw a rectangle on the canvas 
            // will be replacing this with an image --> https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
            //ctx.drawImage('../img/Caterpillar.png', 3, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
        }
        this.eatingPoints = 1,
        this.increaseEatPoints = function () {
            this.height += this.eatingPoints
            this.width += this.eatingPoints
        }
        this.increaseSleepPoints = function () {
            if (caterpillar.x > bed.x 
                && caterpillar.x + caterpillar.width < bed.x + bed.width
                && caterpillar.y > bed.y
                && caterpillar.y + caterpillar.height < bed.y + bed.height
            ){ 
                console.log('zzzzzzzzz   zzzzzzzzz zzzzzzzz')
                console.log('current opacity,',this.opacity)
                this.opacity += 0.007
                this.color = `rgba(35, 224, 72, ${this.opacity})`
            }
        }
    }
}
// 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")
}
```js
// 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()
    food.render() //<-- THE ISSUE IS HERE
}

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..

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)
}
const screenRefresh = () => {
    console.log('screen refreshed!')
    ctx.clearRect(0,0,500,500)
    caterpillar.increaseSleepPoints()
    bed.render()
    caterpillar.render()
    food.render() //--> THE ISSUE IS HERE
}

//add event listeners
document.addEventListener('DOMContentLoaded', function() {
    document.addEventListener('keydown', movementHandler)
    document.addEventListener('keydown', eat)
    createFood()
    setInterval(screenRefresh, 50) // refresh screen every 50 ms
})

Paste a link to your repository here

https://github.com/dnierman0920/game-project-Caterpillar

davidnierman commented 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() 
}
davidnierman commented 2 years ago

I am leaving this open, because something is telling me this might not be the best way to solve this issue.

cory-yonomi commented 2 years ago

This is the way! Good job figuring it out, and thank you for a well constructed issue.