V
V
Vohob Ahmad2020-10-27 15:09:10
JavaScript
Vohob Ahmad, 2020-10-27 15:09:10

Checking for collision with objects (walls)?

How to check if a square hits a wall?

https://codepen.io/Mbreti/pen/YzqMoEP

class WallObj {
    constructor(obj) {//x, y, w, h, bern ,thru) {
        this.x = obj.x
        this.y = obj.y
        this.w = obj.w
        this.h = obj.h
        this.bern = obj.bern
        this.thru = obj.thru
        this.hide = obj.hide
        this.id = obj.id
    }

    collusionWall(startPosition, endPosition) {
        var xS = startPosition[0]
        var x = endPosition[0]

        if (xS - x > 0)
            if (x)
                // if wall behind point
                if (this.x < startPosition[0])
                    return endPosition
                else if (this.x + this.w < x)
                    return endPosition

        return endPosition

        // return [this.x, endPosition[1]]
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-10-27
@dimoff66

const checkIntersection = (obj1, obj2) => 
  (
    (obj1.x >= obj2.x && obj1.x <= obj2.x + obj2.w) // левая сторона первого объекта в границах второго
    ||  // или 
    (obj2.x >= obj1.x && obj2.x <= obj1.x + obj1.w)  // левая сторона второго объекта в границах первого
  )

  &&

  (
    (obj1.y >= obj2.y && obj1.y <= obj2.y + obj2.h) // верхняя планка первого объекта в границах второго
     ||  // или 
    (obj2.y >= obj1.y && obj2.y <= obj1.y + obj1.h) // верхняя планка второго объекта в границах первого
  )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question