SebaPasto
SebaPasto

Reputation: 21

Phaser 3 our squirrel enemies dont care about colliders

So we are making a game in Phaser 3 and basically, the squirrels disregard any type of collider they should collide against walls, and they even have a collider against the obstacles (walls), but for some reason they walk through them.

We have tried putting a collider between the obstacles and the squirrels and a collider between the player character and the squirrels, In the case of the walls/obstacles they walk right through and in the case of the player if you walk against them, you can push them, but if you stay still they walk through you. Its pretty weird, if anyone can help it would be greatly appreciated.

Here is the code for the city scene we are using:


   import Phaser from "phaser";
   import events from "./EventCenter";
   import Player from "../components/Player";
   import Enemies from "../components/Enemies";
import Hitbox from "../components/AttackHitbox";
import Npc from "../components/Npc";

export default class City extends Phaser.Scene {
  constructor() {
    super("City");
    this.level;
    this.hp;
    this.experience;
    this.player;
    this.velocityPlayer;
    this.squirrels = []
    this.squirrelsKilled = 0;
    this.squirrelsKilledText = null;
    this.damageAmount;
    this.enemyHp;
  }

   init(data){
      this.level= data.level || 1
      this.hp= data.hp || 200
      this.experience= data.experience || 0
      this.velocityPlayer= data.velocityPlayer || 400
      this.velocitySquirrel= data.velocitySquirrel || 100
      this.enemyHp = data.enemyhp || 200     
      this.damageAmount = data.damageAmount || 100
      this.squirrelsKilled = data.squirrelsKilled || 0 

}

   create(){
     const map = this.make.tilemap({ key: "City" });
     const layerbackGround = map.addTilesetImage("TDJ2 - tileset", "Mapcity");
     const background = map.createLayer("Ground", layerbackGround, 0, 0);

     this.player = new Player (
      this,
      60,
      2700,
      "C4",
      this.velocityPlayer
   );

     const top = map.createLayer("Top", layerbackGround, 0, 0);
    
  const layerObstacle = map.addTilesetImage(
   "TDJ2 - tileset","Mapcity",
 
  );
  const Obstacle = map.createLayer(
    "Deco",
    layerObstacle,
    0,
    0
  
  );
  const objectsLayer = map.getObjectLayer("Objects");
  this.collectible = this.physics.add.group();
  this.collectible.allowGravity= false
    objectsLayer.objects.forEach((objData) => {
      //console.log(objData.name, objData.type, objData.x, objData.y);

      const { x = 0, y = 0, name } = objData;

      switch (name) {
        case "cura": {
          // add star to scene
          // console.log("estrella agregada: ", x, y);
          const collectible1 = this.collectible
            .create(x, y, "cura")
            .setScale(0.4)
            .setSize(200, 200);
          break;
        }
        }
      })

  this.playersGroup = this.physics.add.group();
  this.collectibleGroup=this.physics.add.group();
  this.squirrelGroup=this.physics.add.group();

     this.hitbox = new Hitbox (
      this,
      this.player
   );

this.squirrels.push(new Enemies(this, 500, 2300, "Squirrel", this.velocitySquirrel));
this.squirrels.push(new Enemies(this, 800, 2500, "Squirrel", this.velocitySquirrel));
this.squirrels.push(new Enemies(this, 1000, 2700, "Squirrel", this.velocitySquirrel));
this.squirrels.push(new Enemies(this, 900, 2900, "Squirrel", this.velocitySquirrel));


  Obstacle.setCollisionByProperty({ colision: true });
  
   this.cameras.main.startFollow(this.player);
   this.physics.world.setBounds(0, 0, map.widthInPixels, map.heightInPixels);
   this.cameras.main.setBounds(0, 0, map.widthInPixels, map.heightInPixels);

  this.physics.add.collider(this.player, Obstacle);
  this.physics.add.overlap(this.player, this.squirrels);
  this.physics.add.overlap(this.squirrels, this.player);
  this.physics.add.collider(this.squirrels, Obstacle);
  this.physics.add.overlap(this.player, this.squirrels,this.DamageTaken,null,this);
  this.physics.add.overlap(this.player, this.collectible,this.heal,null,this);
  this.physics.add.overlap(this.player, this.Eagle,this.mission,null,this);

  for (const squirrel of this.squirrels) {
   squirrel.targetX = Phaser.Math.Between(600, 2800);
   squirrel.targetY = Phaser.Math.Between(600, 2800);
   squirrel.velocity = 300;
   }

   console.log(this.player)
   this.physics.add.overlap(this.hitbox, this.squirrels, this.playerHitEnemy, null, this);

   this.squirrelsKilledText= this.add.text(1000,60,"Squirrels Killed: 0",{
    fontSize : "50px",
    
  }).setVisible(false);
  this.squirrelsKilledText.setScrollFactor(0)

 } 
   update() {
     this.player.update();
     this.hitbox.update();
     
     
     for (const squirrel of this.squirrels) {
      
       const deltaX = squirrel.targetX - squirrel.x;
       const deltaY = squirrel.targetY - squirrel.y;
       const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
 
     
     if (Math.abs(deltaX) > Math.abs(deltaY)) {
       // Movimiento horizontal
       if (deltaX > 0) {
         squirrel.anims.play('walk-right', true);
       } else {
         squirrel.anims.play('walk-left', true);
       }
     } else {
       // Movimiento vertical
       if (deltaY > 0) {
         squirrel.anims.play('walk-down', true);
       } else {
         squirrel.anims.play('walk-up', true);
       }
     }
     
     
   
     if (distance > 2) {
       // Calcular la dirección del movimiento
       const directionX = deltaX / distance;
       const directionY = deltaY / distance;
 
       // Calcular la cantidad de movimiento en este fotograma
       const movementX = directionX *squirrel.velocity * this.game.loop.delta / 1500;
       const movementY = directionY * squirrel.velocity * this.game.loop.delta / 1500;
 
       // Actualizar las coordenadas de la ardilla
      squirrel.x += movementX;
     squirrel.y += movementY;
     } else {
       
       squirrel.targetX = Phaser.Math.Between(100, 1920);
       squirrel.targetY = Phaser.Math.Between(100, 1080);
     }
    
}}

DamageTaken(player, squirrel){
  if (squirrel.active) {
    console.log("choque");
    this.hp--;
    events.emit("UpdateHP", { hp: this.hp });
  }
  
  if(this.hp <= 0){
    

    if (squirrel && squirrel.anims.isPlaying) {
      squirrel.anims.pause();
    }

   
        // Destroy each squirrel individually
    for (const s of this.squirrels) {
      s.destroy(true, true);
    }
    
        // Clear the squirrels array
    this.squirrels = [];

    
    this.scene.pause("City");
    this.scene.launch("GameEnd");
  }
}


}

Upvotes: 0

Views: 90

Answers (1)

winner_joiner
winner_joiner

Reputation: 14870

The problem is you are setting the position on the squirrels manually:

  ...
  // Actualizar las coordenadas de la ardilla
  squirrel.x += movementX;
  squirrel.y += movementY;

And you should be only setting the velocity, if you want the physics / collisions to work.

Mini demo

document.body.style = 'margin:0;';

class DemoScene extends Phaser.Scene{
    create () {
        this.add.text(10,10, 'Mini Physics Demo')
            .setScale(1.5)
            .setOrigin(0)
            .setStyle({fontStyle: 'bold', fontFamily: 'Arial'});

        let squirrel = this.add.rectangle(50, config.height -20, 20, 20, 0xffffff);
        // not-static Object
        this.physics.add.existing(squirrel);
        
        let floor = this.add.rectangle(0, config.height, config.width, 10, 0xcdcdcd)
          .setOrigin(0, 1);
        // static Object
        this.physics.add.existing(floor, true);
          
        let wall1 = this.add.rectangle(100, config.height-20, 20, 20, 0xff0000)
          .setOrigin(0, 1);
        // not-static Object
        this.physics.add.existing(wall1);
          
        let wall2 = this.add.rectangle(150, config.height-10, 20, 20, 0xcdcdcd)
          .setOrigin(0, 1);
        // static Object
        this.physics.add.existing(wall2, true);
        
        this.physics.add.collider(floor, squirrel);
        this.physics.add.collider(floor, wall1);
        
        this.physics.add.collider(wall1, squirrel);
        this.physics.add.collider(wall2, squirrel);
        this.physics.add.collider(wall1, wall2);
        
        squirrel.body.setVelocityX(50)
    }
}

var config = {
    type: Phaser.AUTO,
    width: 536,
    height: 183,
    physics: {
        default: 'arcade',
        arcade: { gravity: { y: 50 }}
    },
    scene: DemoScene ,
    banner: false
}; 

new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>

Upvotes: 2

Related Questions