Pixi js - 需要制作可点击的背景

Mak*_*sim 3 javascript pixi.js

我需要能够单击背景并获取单击的位置。

我尝试向舞台添加一个事件侦听器,如下所示

app.stage.interactive = true;
app.stage.on('click', function(){
    console.log('hello');
})
Run Code Online (Sandbox Code Playgroud)

但只有当我单击舞台内的元素而不是背景本身时它才有效。

我是否需要制作一个精灵作为背景,如果需要,我如何设置其背景颜色并确保它位于所有其他元素下方?

Iro*_*com 6

舞台是一个 PIXI.Container,这意味着它基本上是一个可以容纳子节点的空节点。它没有自己的维度,因此当交互管理器对您的点击进行命中测试时,不会检测到它。

您添加背景精灵的建议可能是最简单的解决方案。您可以像这样添加一个:

// Create the background sprite with a basic white texture
let bg = new PIXI.Sprite(PIXI.Texture.WHITE);
// Set it to fill the screen
bg.width = app.screen.width;
bg.height = app.screen.height;
// Tint it to whatever color you want, here red
bg.tint = 0xff0000;
// Add a click handler
bg.interactive = true;
bg.on('click', function(){
  console.log('hello');
});
// Add it to the stage as the first object
app.stage.addChild(bg);

// Now add anything else you want on your stage
...
Run Code Online (Sandbox Code Playgroud)

PixiJS 按顺序渲染对象,因此如果您将背景精灵添加为应用程序舞台的第一个子元素,它将渲染在所有其他内容的后面。当对点击进行命中测试时,它将是最后一个测试的对象,因此将捕获舞台背景上的点击。请注意,要“阻止”点击,其他对象需要设置为 Interactive = true,即使它们没有附加点击处理程序!