Check if sprite / image / emitter is in camera viewport

Hi,
I can’t find answer in demos and documentation…
Is there any build-in function to simply determine
IF something IS IN CAMERA VIEWPORT?
(element is visible on screen)

I need to turn on some particle emitters when sprite followed with camera is close to them, but I need to do it before it’s seen by camera

You can use, e.g.,

this.cameras.main.worldView.contains(X, Y)
4 Likes

Ok, this works… but can I add to camera like extra space?
I need to have 100px around camera view to detect contains sooner…

Is it possible?

You can copy the worldView rectangle and inflate it. See the Rectangle methods.

tested this theory in my own app, this worked for me (change the respective offsets you need for your app).

const offsetleftx = 50;
const offsetrightx = 50;
const offsettopy = 100;
const offsetbottomy = 200;
this.extendedview = new Phaser.Geom.Rectangle(
 this.cameras.main.worldView.x - offsetleftx,
 this.cameras.main.worldView.y - offsettopy,
 this.cameras.main.worldView.width + offsetrightx + offsetleftx,
 this.cameras.main.worldView.height + offsetbottomy + offsettopy
)
//this.extendedview
//Rectangle {x: 190, y: 57.875, width: 580, height: 534.25}
//this.cameras.main.worldView
//Rectangle {x: 240, y: 157.875, width: 480, height: 234.25}
1 Like

or if you need to call this often (say your worldview was changing with zoom), a function:

this.extendedview = (offsetleftx, offsetrightx, offsettopy, offsetbottomy) => {
    return new Phaser.Geom.Rectangle(
     this.cameras.main.worldView.x - offsetleftx,
     this.cameras.main.worldView.y - offsettopy,
     this.cameras.main.worldView.width + offsetrightx +offsetleftx,
     this.cameras.main.worldView.height + offsetbottomy + offsettopy
    )
}
const bigview = this.extendedview(50,50,100,200)
//Rectangle {x: 190, y: 57.875, width: 580, height: 534.25}

Thanks :wink:

camera.cull([ gameObject ]).length > 0

is another way.

1 Like
Phaser.Geom.Rectangle.Overlaps(
  sprite.getBounds(),
  camera.worldBounds
)

In Phaser v3.60 particle emitters will also have getBounds().

1 Like