Owen Ffrancon Owen Ffrancon - 3 years ago 133
Javascript Question

Problems with making "Catch the falling hair" game

I know, this is a strange one. I'm trying to make a simple Javascript game where:


  1. The player has to catch the randomly falling head hair.

  2. The hair returns to the head when caught.

  3. Catching the falling hair increases the Score

  4. The hair falls faster and faster over time.

  5. If all of the hair falls then it's GAME OVER.



I've given it a go, and copied most of it to my fiddle here, which is an abstract version of what I'm trying to achieve.

Current Javascript:

$(document).ready(function(){

//randomize hair initial rotation
$('.hair').each(function(){
var random = Math.random()*360;
var degree = "rotate("+random+"deg)";
$(this).css("transform",degree);
});

//set points to 0
$('#points').text(points);
});

function startGame() {
start = true;
var level = 1;

//move catcher with hand
$( document ).on("mousemove", function(event) {
var catcherX = event.pageX - 50;
$('#catcher').css("left",catcherX);
});


$('.hair').each(function() {
var wait = Math.ceil(Math.random()*10000)/level;
randomX = Math.random()*($('#gameDiv').width());

function makeDestination(hair) {
hair.css("top", 510);
hair.css("left", randomX);
}

setTimeout(makeDestination($(this)), wait)
})
};

startGame();


The biggest problems I'm having are:


  1. How can I make the hair fall after a random interval?
    wait
    currently isn't doing anything in the
    setTimout
    function.

  2. How can I make the hair function start again after being caught?



I also feel like there must be a much better way of writing this game, what do you guys think?

Answer Source

I made the setTimeout reference the function instead of calling it immediately (putting the parens calls it and references the return value, putting just the function name references). Then I tweaked the transition to animate the top over 3 seconds while the left takes just 1 second. Then I made makeDestination call itself after a delay. Lastly, the "hair" needs to jump back up to the top, so I change the transition to be immediate, change the CSS, then change the transition back to animate.

https://jsfiddle.net/9pq6xfxc/1/

I leave it to you to detect the intersection of the cyan box and the hair. While this can obviously be done on mouse movement, it's going to be trickier to find the hairs that fall on a stationary hand.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download