It is my first time using Phaser3 and I am trying to create a game to display in a website. My plan was to make a vertical map that you can navigate either with the keys and scrolling. The thing is that I do not find any examples online, since if the camera follows the character, I do not manage to make the scroll work, and the other way around. Here is a snipet of my code in case it helps
//Creo la configuracion del juego
const config = {
type: Phaser.AUTO,
width: window.innerWidth,
height: 2000,
scale: {
mode: Phaser.Scale.NONE,
parent: 'game',
autoCenter: Phaser.Scale.CENTER_BOTH
},
backgroundColor: '#000000', //fondo
parent: 'game', //Donde se va a renderizar
physics:{
default: 'arcade', // arcade, impact o matery
arcade: {
gravity: {y: 300},
debug: false
}
},
scene: {
preload: preload, //cargamos imagenes, recursos etc
create: create, //usamos esas imagenes, recursos
update: update //se actualiza contantemente
}
}
//Inicializo el juego con la configuracion
new Phaser.Game(config);
function preload(){ //1
this.load.image(
'dessert-background',
'assets/background/dessert-bg.jpg'
);
//Sprite character
this.load.spritesheet(
'hero', //id, solo puede haber uno con ese id
'assets/entities/hero_sprite.png',
{frameWidth:64, frameHeight: 64}
);
}
function create(){ //2
let bg = this.add.image(0, 0, 'dessert-background')
.setOrigin(0, 0);
bg.displayWidth = this.sys.game.config.width;
bg.displayHeight = this.sys.game.config.height;
bg.alpha = 0.3; //transparencia
window.addEventListener('resize', () => {
bg.displayWidth = document.documentElement.clientWidth - scrollbarWidth
});
this.hero = this.physics.add.sprite(50,100,'hero')
.setOrigin(0,1)
.setCollideWorldBounds(true)
.setGravityY(300);
this.physics.world.setBounds(0,0,config.width, 2000);
this.cameras.main.setBounds(0,0,config.width, 2000);
this.cameras.main.startFollow(this.hero, true, 0.1, 0.1); // Suavizado de seguimiento
createAnimations(this);
this.keys = this.input.keyboard.createCursorKeys();
}
If you only want to move the camera with the scroll-wheel, you can use the the input-event wheel
(link to the documentation).
And just move the camera, by setting the scrollY
property.
Short demo:
const config = {
width: 500,
height: 180,
scene: {
create
}
}
function create(){
let label = this.add.text(10, 10, 'Demo Scroll to move the camera up or down')
.setOrigin(0);
this.add.line( 0, 1300, 0, 0, 500, -2600, 0xffff00 )
.setOrigin(0);
this.input.on('wheel', function(pointer){
if(pointer.deltaY > 0){
this.cameras.main.scrollY += 10;
} else if(pointer.deltaY < 0){
this.cameras.main.scrollY -= 10;
}
});
}
new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>