欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

pixi.js 碰撞检测

程序员文章站 2024-03-15 21:47:24
...
        let container = new PIXI.Container() //创建容器存放障碍物
        for (var i = 0; i < 10; i++) {
          // 创建障碍物
          let obstacle = new PIXI.Sprite(PIXI.Texture.from('https://img.alicdn.com/imgextra/i2/39767794/O1CN01lzcmmi27RhbhlMlhW_!!39767794.png'))
          let flags = true //控制碰撞,碰撞后避免持续触发碰撞函数
          obstacle.x = Math.random() * application.screen.width
          obstacle.y = Math.random() * application.screen.height
          container.addChild(obstacle)
          application.stage.addChild(container)
          application.ticker.add(() => {
            obstacle.y += 2
            if (this.hitTestRectangle(obstacle, firfox)) {
              if (flags) {
                container.removeChild(obstacle) //碰撞后删除元素
                flags = false
              }
            }
          })
        }

检测碰撞函数

      // 碰撞检测
      hitTestRectangle(r1, r2) {
        //Define the variables we'll need to calculate
        let hit, combinedHalfWidths, combinedHalfHeights, vx, vy;
        //hit will determine whether there's a collision
        hit = false;
        //Find the center points of each sprite
        r1.centerX = r1.x + r1.width / 2;
        r1.centerY = r1.y + r1.height / 2;
        r2.centerX = r2.x + r2.width / 2;
        r2.centerY = r2.y + r2.height / 2;
        //Find the half-widths and half-heights of each sprite
        r1.halfWidth = r1.width / 2;
        r1.halfHeight = r1.height / 2;
        r2.halfWidth = r2.width / 2;
        r2.halfHeight = r2.height / 2;
        //Calculate the distance vector between the sprites
        vx = r1.centerX - r2.centerX;
        vy = r1.centerY - r2.centerY;
        //Figure out the combined half-widths and half-heights
        combinedHalfWidths = r1.halfWidth + r2.halfWidth;
        combinedHalfHeights = r1.halfHeight + r2.halfHeight;
        //Check for a collision on the x axis
        if (Math.abs(vx) < combinedHalfWidths) {
          //A collision might be occurring. Check for a collision on the y axis
          if (Math.abs(vy) < combinedHalfHeights) {
            //There's definitely a collision happening
            hit = true;
          } else {
            //There's no collision on the y axis
            hit = false;
          }
        } else {
          //There's no collision on the x axis
          hit = false;
        }
        //`hit` will be either `true` or `false`
        return hit;
      }

上一篇: L2-012. 关于堆的判断

下一篇: