WDI-SEA / game-project-issues

0 stars 0 forks source link

trying to figure out hit detection #42

Closed anaismveras closed 3 years ago

anaismveras commented 3 years ago

What's the problem you're trying to solve?

I have my trash moving towards my player but I cant seem to find a way to if my player hits the trash than than trash.alive = false and it adds to the point system

Post any code you think might be relevant (one fenced block per file)

let trashArray = []
let beachGoerArray = []

//game loop
const gameLoop = () => {
    ctx.clearRect(0, 0, 750, 300)
    trashArray.forEach((trashitem) => {
        ditectTrashHit()
        trashitem.render()
        trashitem.x += 3
    })

function Trash (x, y, color, width, height) {
    this.x = x
    this.y = y
    this.height = height
    this.color = color
    this.width = width
    this.alive = true
    this.render = function() {
        ctx.fillStyle = this.color
        ctx.fillRect(this.x, this.y, this.width, this.height)
    }
}

const createTrash = () => {
    let generateRandomY = Math.floor(Math.random() * ctx.height)
    let garbage = new Trash(1, generateRandomY, 'red', 10, 20)
    if (garbage.y <=0) {
        garbage.y = 0
    }
    if (garbage.y + garbage.height >= ctx.height) {
        garbage.y = ctx.height - garbage.height
    }
    trashArray.push(garbage)
    console.log(trashArray)
}
const trashInterval = setInterval(createTrash, 3000)
const ditectTrashHit = () => {
    for (let i = 0; i < trashArray.length; i++) {
        if (galleria.x < trashArray[i].x + trashArray[i].width && galleria.y + galleria.height < trashArray[i].y + trashArray[i].height) {
            trashArray[i].alive = false
            trashPoints.innerText = `Trash:${trashArray.length}/40`
        }
    }
}

If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

no error messages

What is your best guess as to the source of the problem?

I'm not sure if i am targeting each of the trashes wrong?

What things have you already tried to solve the problem?

i have tried moving a few times around, and doing a for loop that

anaismveras commented 3 years ago

i found a solution

TaylorDarneille commented 3 years ago

awesome!!