2

And I have a function that reads in level data. This is the snippet in question; actors is an array and I'm looping over it until i find an actor of type player.

function Level(plan) {
   //Cut snippet..........
    this.player = this.actors.filter(function(actor) {
        return actor.type == "player";
    });

    console.log(this.player);
//................  
}

The player object,

function Player(pos) {
    this.pos = pos
    this.size = new Vector(0.8, 1.5);
    this.speed = new Vector(0, 0);
}
Player.prototype = new Actor();
Player.prototype.type = "player"

The issue is that in the console, the

console.log(this.player)

will show all the correct details, but when i try to log the position for example

console.log(this.player.pos)

I get undefined. Its a simple program, I'm not using ajax or anything. Thought it might be do with execution order, can someone explain this to me and a solution? If it is todo with execution order, an explanation would be much appreciated.

Thank you very much, Rainy

2 Answers 2

3

You get undefined because when you filter your actor array, you get a new array as a result. So console.log(this.player) outputs an array, not a single object.

You need to get the first element of the array this.player to output its pos property.

Something like this:

if(this.player.length > 0) 
    console.log(this.player[0].pos);
Sign up to request clarification or add additional context in comments.

Comments

0

Use reduce instead of filter for a single player.

  this.player = this.actors.reduce(function(current, actor) {
      return actor.type === 'player' ? actor : current;
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.