I’m having an issue with cameras.main.worldView.contains and detecting if a sprite is in the ‘Viewport’ of the window. It seems to only detect the centre of the sprite not accounting for the full height of it.
I’m using scrollY to fade the sprite in at a certain point, but I want to detect if it’s in the window or not and then fade in instead. For whatever reason the height of the sprite is not taken into consideration only the centre point.
Seems using worldCollide.contains with Y will only detect the ‘origin point’ of a sprite so if setOrigin is 0 it will detect it only at the top, .5 will be the middle etc. As soon as that small point is off screen it becomes ‘False’
So I ended up just writing a function to handle detection of the top, middle and bottom of the sprite.
I can also set an offset at the top and bottom if I want it to animate in quicker or slower etc.
Is there a better way than this?
detectViewport(sprite, offset1, offset2) {
if (this.cameras.main.worldView.contains(sprite.body.x, sprite.body.y + offset1) ) { //TOP POINT + OFFSET IF NEED BE
text.setText('In Viewport: True');
this.tweens.add({
targets: sprite,
alpha: 1,
ease: 'Power1',
duration: 400,
scale: 1
});
}
else if (this.cameras.main.worldView.contains(sprite.x, sprite.y)) { //MID POINT
text.setText('In Viewport: True');
}
else if (this.cameras.main.worldView.contains(sprite.x, sprite.y + sprite.displayHeight / 2 + offset2)) { //BOTTOM POINT + OFFSET IF NEED BE
text.setText('In Viewport: True');
this.tweens.add({
targets: sprite,
alpha: 1,
ease: 'Power1',
duration: 400
});
} else {
text.setText('In Viewport: False');
graphics.clear();
this.tweens.add({
targets: sprite,
alpha: 0,
ease: 'Power1',
duration: 400
});
}
}
Thanks for the info. Forgive my ignorance but I don’t understand how this detects if the sprite is in the viewport or not. Console logging this returns a huge array and no obvious ‘visible true/false’
The following just always returns true even if the sprite is not in the camera view: