RealAnyOne
RealAnyOne

Reputation: 235

Weird condition behaviour Javascript

I have two functions, one that calculates the mouse distance from an object and the other one calculates the player score. It starts scoring when the mouse is at least 200px away from the object and the closer the mouse is the more score you get.

function calculateMouseDistance() {
    document.onmousemove = handleMouseMove;
    var rect = c.getBoundingClientRect();
    function handleMouseMove(e) {
        mouseX = e.clientX - rect.left;
        mouseY = e.clientY - rect.top;
    }
    mouseDistanceX = object.x - mouseX;
    mouseDistanceY = object.y - mouseY;
    mouseDistance = Math.round(Math.sqrt((mouseDistanceX*mouseDistanceX)+(mouseDistanceY*mouseDistanceY)));
}

function calculateScore() {
    if (mouseDistance<200) {
        score = Math.round(score + (mouseDistance / 100));
    }
    document.getElementById("tester").innerHTML = "Score: " + score + " " + "Distance: " + mouseDistance;
}

For some reason the above results in the score stopping when distance is 50px and below.

I tried outputting the (mouseDistance<200) condition and it was just fine, at 200px distance it said "true" and it only stopped being true above 200px.

If so then the score shouldn't stop updating when mouse is at 50px distance, but it does :P halp

Upvotes: 0

Views: 34

Answers (1)

user4843530
user4843530

Reputation:

When the distance is 50px and below, the added score starts to get at or below 0.5. Rounding removes that added score.

Say the distance is 40px, and the player's score is 150. The new score would be 150.4 (score + mouse distance/100). But when you round that, you get 150, and the score stays the same.

Upvotes: 1

Related Questions