So i'm trying to make a "game" with javascipt witc has rectangles that go arround the canvas and they have timers. When rectangles timer goes above certain limit rectangle gets a new direction.
I'm trying to make the rectangles with class so i can have multiple of them running at same time. But the problem is that i cant get the functions inside of the class pass data to eachother (i think that's the problem...).
On the draw function this.cubeLocX is not defined
and this.ctx.fillStyle="#2a2b2d"; gets error Cannot set property 'fillStyle' of undefined
class cubeV3 {
constructor(canvas) {
//var canvas = document.getElementById('canvas');
this.canvas = canvas;
this.cubeLocX = 100;
this.cubeLocY = 0;
this.speed = getRandomNumber();
this.dir = 0;
this.turnTimer = 0;
this.turnTimerMax = getRandomNumberV2(30,100);
this.ctx = this.canvas.getContext("2d");
}
testClass() {
alert('This is CubeV3 classes testfunction reporting in!');
/*you have put the call to the private method inside the constructor of the javascript class. in that point the functions are not yet initialized
but if you initialize the object like so:
var test = new MyObject();
and then do this:
test.myMethod();
it will work.*/
}
update() {
this.turnTimer ++;
if (this.turnTimer > this.turnTimerMax) {
this.dir = this.turnTimerMax = getRandomNumberV2(1,4);
this.turnTimer = 0;
this.turnTimerMax = getRandomNumberV2(30,100);
}
if (this.dir == 1) {this.cubeLocY -=this.speed;}//UP
if (this.dir == 2) {this.cubeLocY +=this.speed;}//DOWN
if (this.dir == 3) {this.cubeLocX -=this.speed;}//LEFT
if (this.dir == 4) {this.cubeLocX +=this.speed;}//RIGHT
}
draw(self,) {
//this.cubeLocX = 555;
resetCanvas();
console.log(this.cubeLocX);
alert(this.cubeLocX);
this.ctx.fillStyle="#2a2b2d";
this.ctx.fillRect(this.cube_loc_x,this.cube_loc_y,25,25);
}
}
So how can i make my class work?
EDIT calling the class This is placed after the draw for calling and updating the class
//setInterval(resetCanvas,10)
var testCube = new cubeV3(canvas);
setInterval(cube, 10);
//setInterval(testCube, 10);
setInterval(testCube.update, 10);
setInterval(testCube.draw, 10);