Reputation: 99
This code throw an error - "cannot read property 'x' of undefined". I wanted to assign this function and call it later with an argument (function "crash" answer the question about the collision with other object).
function Obj(x, y, height, width, type) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
if(type == "obstacle") {
this.speedX = levelManager.level;
}
var self = this;
this.isNotUsed = function() {
return self.x < 0;
};
this.drawSelf = function(img) {
ctx.drawImage(img, self.x, self.y, self.width, self.height);
};
if(type == "hero"){
this.crash = function(otherObj) {
var myLeft = this.x;
var myRight = this.x + this.width;
var myBottom = this.y + this.height;
var otherLeft = (otherObj.x) || 0; //error occurs here
var otherRight = (otherObj.x + otherObj.width) || 0;
var otherTop = otherObj.y || 0;
var collision = true;
if((myBottom < otherTop) ||
(myRight < otherLeft) ||
(myLeft > otherRight)) {collision = false;}
return collision;
};
}
}
var hero = new Obj(0, 0, 40, 40, "hero");
Upvotes: 0
Views: 40
Reputation: 7360
The code works well (see snippet). The only error you can have if you call hero.crash()
without any argument. To avoid this, you can change the crash() function adding as first line of the function otherObject = otherObject || {};
. Or better, as suggested in comments, just return if otherObject is undefined:
if (!otherObject) return false;
or if it is not an object
if (typeof otherObject !== 'object') return false;
function Obj(x, y, height, width, type) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
if(type == "obstacle") {
this.speedX = levelManager.level;
}
var self = this;
this.isNotUsed = function() {
return self.x < 0;
};
this.drawSelf = function(img) {
ctx.drawImage(img, self.x, self.y, self.width, self.height);
};
if(type == "hero"){
this.crash = function(otherObj) {
var myLeft = this.x;
var myRight = this.x + this.width;
var myBottom = this.y + this.height;
var otherLeft = (otherObj.x) || 0; //error occurs here
var otherRight = (otherObj.x + otherObj.width) || 0;
var otherTop = otherObj.y || 0;
var collision = true;
if((myBottom < otherTop) ||
(myRight < otherLeft) ||
(myLeft > otherRight)) {collision = false;}
return collision;
};
}
}
var hero = new Obj(0, 0, 40, 40, "hero");
console.log('THIS IS PRINTED')
console.log(hero.crash('{}'));
console.log('BUT FROM HERE NO MORE');
console.log(hero.crash());
Upvotes: 1