I'm trying to do more OOP in Javascript. One thing i can't figure out is how can i modify a variable inside an object from another function?
Here's how I tried to do it:
function Ball(){
radius = 5;
Y = 20;
X = 25; // The value i would like to change.
ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
ctx.fillStyle = '#00ff00';
ctx.fill();
}
function draw(){
Player();
Ball();
}
function update(){
ctx.clearRect(0, 0, 800, 400);
draw();
Ball.X++; // This is where i want to modify the value.
}
So far I've only been able to do it if I define X as a global variable, but I dont want to do that since there are other X and Y values.
So how would i access the variable from outside the function?
EDIT: The solution provided by "nnnnnn" worked to an extent, it changes the X value but I ran into another problem. My clearRect doesnt clear the animation, so instead of a ball it draws a line that just grows.
This is what the code looks like right now:
function Ball(){
this.radius = 5;
this.Y = 20;
this.X = 25;
this.draw = function() {
ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
ctx.fillStyle = '#00ff00';
ctx.fill();
};
}
var ball = new Ball();
function draw(){
Player();
ball.draw();
}
function update(){
ctx.clearRect(0, 0, 800, 400);
draw();
ball.X++;
}
I have tried moving it around, placing it both in the draw() and ball.draw() functions, but still getting the same result, I also tried doing a fillRect instead of clear but it didnt help. Anyone able to see whats wrong?