Jump to content

Casting


ManBoy
 Share

Recommended Posts

Hi, how do I cast in JavaScript?

function ballHitBrick(ball, brick){	console.log(Phaser.Group(brick.parent));	console.log(brick.parent as Phaser.Group);}

I tried the code above and this error came out:

 

 

  1. Uncaught TypeError: Cannot call method 'addChild' of undefined phaser.min.js:5
    1. ballHitBrickBreakout.js:164
    2. c.Physics.Arcade.collideSpriteVsGroupphaser.min.js:12
    3. c.Physics.Arcade.collideHandlerphaser.min.js:12
    4. c.Physics.Arcade.collidephaser.min.js:12
    5. c.StateManager.updatephaser.min.js:4
    6. c.Game.updatephaser.min.js:5
    7. c.RequestAnimationFrame.updateRAFphaser.min.js:8
    8. window.requestAnimationFrame._onLoopphaser.min.js:8
    9.  

 

Link to comment
Share on other sites

I already created a custom class. What I need is for the collider in the event, in this case, the brick.parent to recognize it as Brick (extending Phaser.Group that contains separate sprites e.g:eyes, mouth etc), so it can retrieve a public variable I defined it in.

 

In case of the example you've given, I need something like this:

MonsterGroup = function (game, image, action) {    Phaser.Group.call(this, game);    this.hobby = 'algebra';}
function playerHitMonster(player,monster){	console.log(monster.parent.hobby);	//console.log((monster.parent as MonsterGroup).hobby);}

Since I can't cast in JavaScript, I'm kinda lost how to recognize the collider's parent as MonsterGroup to retrieve its hobby.

Link to comment
Share on other sites

You can just check if the object contains the field you are looking for, and then expect the object to be the type you expect it to be:

if (monster.parent.hobby) { // given that you trust monster to always have a parent property to begin with  console.log(monster.parent.hobby);}

It's probably not the cleanest way, but it should do the trick as long as you are not storing booleans in the property that you are testing.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...