Retrieving game object info when pressing on object

Hi there!

I’m working on interaction between a player and an npc and I’ve run into a problem. I want the npc to be clickable and its input area to my desired size.

I’m using a state machine to manage the states.

    scene.input.on('gameobjectdown', (pointer, object) => {
      scene.input.off("pointerdown")
      // attack
    })

I figured this would help a lot. While it works, I can’t change the input area of the object to my desired size. The npc width and height are 96 by 96, and its hit input area starts as 96 by 96 and I can’t seem to change it.

this.body.setSize(20, 20)

I set this in the NPC class. I realize it doesn’t change the hit area, which is part of my problem.

So another way I tried was to create a zone that follows the x and y of the npc. I used setInteractive to make it possible to interact with the zone. And that worked great except for the fact I’m no longer retrieving the NPC game object data.

I’m not entirely sure what to research in reference to this. So I’m a bit stumped. But hoping someone can lend me some clues about how I can achieve this.

I wrote a codepen to demonstrate this here.

Any comments or advice would be much appreciated.

You can set the hitarea.
Example.

1 Like

So I had a look and come up with this so far:

    // create graphics
    this.graphics = scene.add.graphics();
    
    // create rectangle
    this.zone = new Phaser.Geom.Rectangle(0, 0, 30, 30);
    this.setInteractive(this.zone, Phaser.Geom.Rectangle.Contains)
    this.setActive(true)
    
  }
  update() {
    this.zone.x = this.x - 18
    this.zone.y = this.y - 10
    
    this.graphics.lineStyle(2, 0xff0000);
    this.graphics.strokeRectShape(this.zone);
    
  }

I should mention this code is inside the NPC class. I’m calling setInteractive from there.
This doesnt seem to be working for me, so I know I’m doing something wrong. So when I’m giving the setInteractive function a shape, its assigning the interaction of the game object to the rectangle instead, I think :grimacing:. I’m unsure how to go about this. I’ll keep working with it for now.

I’ve updating the codepen to reflect where I’m currently at.

    this.setInteractive(this.zone, Phaser.Geom.Rectangle.Contains).on('pointerover', function(pointer, localX, localY, event){
    // ...
      console.log("touched")
});

The hitbox seems to off on the x axis. I’m unsure why thats happening.

Edit: Okay, I believe I got it to work. I got a bit confused about its position. It seems to appear in the left top corner of the sprite I’m using. But it is working.

1 Like

Keep it up. I’m sure you will make a great game :slight_smile: