I am playing with html5 canvas to create bouncing balls. I have this all working but I have to call an initialise function to set certain properties. How can I do this automatically in the constructor without having the initializer firing when the properties are accessed?
var test1 = new Ball(20);
test1.setAngleAndVelocity(); //I dont want to have to call this.
function Ball(speed){
this.position = new Vector2(canvas.width / 2, canvas.height / 2);
this.velocity;
this.speed = speed;
this.angle;
this.setAngleAndVelocity = function(){
this.angle = Math.floor(Math.random() * 360) * 0.0174532925;
this.velocity = new Vector2(this.speed/10 * Math.cos(this.angle), this.speed/10 * Math.sin(this.angle));
}
}
Since
setAngleAndVelocity()is a static method, I’d recommend putting it in the prototype of yourBallclass:this.velocity;andthis.angle;aren’t necessary: They’re not defining anything, and the only use they serve is to show the developer what properties may be defined.After these modifications, your script has become more efficient, and can be used in this way: