Uncaught TypeError: Cannot read property 'set' of undefined

让人想犯罪 __ 提交于 2019-12-25 17:37:41

问题


I've made a constructor (and put it above preload function) like this

character = function(CharX,CharY,CharSpeed){
this.x = CharX ;
this.y =  CharY;
this.speed = CharSpeed;
this.AddSpriteSheet = function (SprX,SprY,key) {
this.character = game.add.sprite(SprX,SprY,key);}
};

Later in create function I added

var Char1 = new character(game.world.width*0.5,game.world.height*0.5,5);
Char1.AddSpriteSheet(game.world.width*0.5,game.world.height*0.5,'character');
Char1.anchor.set(50,50);

Console reads

"Uncaught TypeError: Cannot read property 'set' of undefined"

What have i done wrong?

Edit : Make error more visible


回答1:


You're making a custom class to represent a character, but it's not a Phaser Sprite, and therefore it doesn't have any of the methods/properties a Sprite does unless you define them yourself. If you want to create your own class to extend Phaser.Sprite, I suggest you look at this forum post and also this example. Just googling "phaser extend sprite" will help you find some other resources as well.

Essentially, you need to do something like this:

function Character(game, x, y) {   
    Phaser.Sprite.call(this, game, x, y, 'sprite key');   
    // define other properties for your character
}
Character.prototype = Object.create(Phaser.Sprite.prototype);
Character.prototype.constructor = Character;

And then you would add all of your Character's methods onto the prototype.




回答2:


Your constructor character does not have a property anchor, thus, Char1.anchor does not exist, and neither does Char1.anchor.set.




回答3:


'set' of undefined" bca "set" is Pixi's compare to "setTo" Phaser's

Char1.anchor.set(50,50); replace by Char1.anchor.setTo(0.5);// 0.5, 0.5 will point to center of the sprite's square, if that is the intention. this is also truth for .scale.setTo();

also if you create new prototype object out of create function i would recommend to follow this example https://phaser.io/examples/v2/games/tanks



来源:https://stackoverflow.com/questions/45081177/uncaught-typeerror-cannot-read-property-set-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!