Pidor4o
Pidor4o

Reputation: 1

I want to catch collision between collision between (mouse) cursor and sprite using phaser

So like, here's the code. I'm really new to all of this, but I wanted to try something like this out for a project I'm assigned at school.

'use strict'
const Game = new Phaser.Game(1920, 1080, Phaser.AUTO, 'game-canvas', { preload, create,update })

let player
let cursors
let speed
let cursor


Game.physics.arcade.enable()

function preload() {


Game.load.spritesheet('mechove','mechove.png',71/2,29/1)

}

function create() {
   
  player = Game.add.sprite(Game.width/2, Game.height/2, 'mechove')
  
  player.scale.setTo(3,3)
  player.anchor.setTo(0.6,0.6)
  Game.physics.arcade.enable(player)
  player.body.collideWorldBounds = true;
  cursors=Game.input.keyboard.createCursorKeys()
  player.body.allowRotation = false;
  player.frame = 1 
}

function update(){
  console.log(Game.input.activePointer.x)
  player.rotation = Game.physics.arcade.moveToPointer(player, 20, Game.input.activePointer, 1000);  
}

P.S. I want to detect collision between the cursor and the sprite 'mechove', because it's spritesheet consists of one bloody sword and one non-bloody, the idea is that when the sword-sprite touches the cursor the bloody one comes up.

Upvotes: 0

Views: 278

Answers (1)

Dabe
Dabe

Reputation: 13

As winner_joiner pointed out, it looks like you're using Phaser 2. The way to achieve this interaction in Phaser 2 is: First enable inputs on the player sprite (this is the case for any GameObject) using the .inputEnabled property:

player.inputEnabled = true;

Then, in the update() functon, you can continually check the pointerOver() function on the input property of player:

function update() {
    if (player.input.pointerOver()) {
        // do something
    }
}

Here's an example with code for this exact scenario. I highly recommend going through the examples catalogue when you want to figure out how to do something in Phaser. They help me a lot.


If using Phaser 3, you can detect the mouse cursor interacting with any GameObject (such as the player sprite) by calling the .setInteractive() function on player and creating a listener for the 'pointerover' on the sprite:

player.setInteractive().on('pointerover', callbackHandleFunc)

The input plugin documentation

The documentation specifically for the pointerover event for a GameObject

Upvotes: 0

Related Questions