When I try to run the following code
var largura = 800,
altura = 500,
mainColor,canvas,ctx,
player = {
x:400,
y:250,
largura:50,
altura:50,
color:"#cc3030"
},
obstaculo = {
obstaculos:[],
time:0,
insert:function(){
this.obstaculos.push({
color:"#3030cc",
altura:20+Math.floor((Math.random()*51)),
largura:40+Math.floor((Math.random()*41)),
y:0-this.altura,
x:Math.floor((Math.random()*largura-this.largura)),
grav:1.5,
velocity:0});
},
update:function(){
if (this.time <= 0) {
obstaculo.insert();
this.time = 10+Math.random()*21;
} else {
this.time--;
}
for (var i = 0;i <= this.obstaculos.length; i++) {
var obj = this.obstaculos[i];
obj.velocity += obj.grav;
obj.y += obj.velocity;
}
obstaculo.draw();
},
draw:function(){
for (var i = 0;i < this.obstaculos.length; i++) {
var obj = this.obstaculos[i];
drawObject(obj.color,obj.x,obj.y,obj.altura,obj.largura);
}
}
};
function main () {
canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.height = altura;
canvas.width = largura;
canvas.addEventListener("mousemove", move);
ctx = canvas.getContext("2d");
mainColor = ctx.createLinearGradient(0,0,0,altura);
mainColor.addColorStop(0,"#aaa");
mainColor.addColorStop(0.5,"#ccc");
mainColor.addColorStop(1,"#aaa");
update();
}
function update(){
draw();
drawObject(player);
obstaculo.update();
requestAnimationFrame(update);
}
function draw(){
ctx.fillStyle = mainColor;
ctx.fillRect(0,0,largura,altura);
}
function drawObject (object) {
ctx.fillStyle = object.color;
ctx.fillRect(object.x,object.y,object.largura,object.altura);
}
function move (e){
player.x = e.clientX-(player.largura/2);
player.y = e.clientY-(player.altura/2);
}
<body style="width: 800px;height: 500px;" onload="main()">
</body>
I get the error TypeError: obj is undefined
on lines 37,71,65 and 1; I understand error occurs when the value of the variable is undefined, but in my view the obj value is set, so that if I type obstaculo.obstaculos[0]
it returns the object to me. Why is it going wrong?