Reputation: 125
I am writing a code for this game where you get a point every time you click on a ball. Your total score should be reflected at the top where the points
variable is keeping your score. However the score is being printed on top of itself each time. Meaning that when you go from 0 points to 1 point, the 1 is printed over the 0 and so on. I know I have to remove or replace the previous score before printing the new one but I am new to JavaScript and I am not sure how to go about this.
My code:
var x = Math.floor(Math.random() * 550);
var y = Math.floor(Math.random() * 350);
var r = 40;
var points = 0;
function setup() {
createCanvas(550,350);
background(0);
}
function draw() {
fill (255)
ellipse (x, y, r, r)
text(("Score:" + points), width/2, 40)
}
function inside(mx, my){
let d = dist(mx, my, x, y);
return d < r - 10;
}
function mousePressed() {
if(inside(mouseX, mouseY)){
points++;
}
}
Upvotes: 2
Views: 130
Reputation: 2205
You could try like this by creating div.
var x = Math.floor(Math.random() * 550);
var y = Math.floor(Math.random() * 350);
var r = 40;
var points = 0;
let scoreDiv = null;
function setup() {
createCanvas(550,350);
background(0);
scoreDiv = createDiv('');
scoreDiv.position(width / 2, 40)
scoreDiv.style('color', '#FFFFFF');
}
function draw() {
fill (255)
ellipse (x, y, r, r)
scoreDiv.elt.innerText = `Score: ${points}`;
}
function inside(mx, my){
let d = dist(mx, my, x, y);
return d < r - 10;
}
function mousePressed() {
if(inside(mouseX, mouseY)){
points++;
}
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>
Upvotes: 2
Reputation: 1341
hmm you can simply use innerText
to display your score
<p id="score"></p>
function mousePressed() {
var hhi = dist (hballx, hbally, mouseX, mouseY)
ellipse (hballx, hbally, hballsize, hballsize)
if (hhi < hballsize/2) {
hballx = (getRandomInt(550))
hbally = (getRandomInt(350))
score = score + 1;
document.getElementById("score").innerText = score; // it will replace the previous score if the score changes
}
}
Upvotes: 0