Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - Uncaught TypeError: Cannot read property 'set' of undefined

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...