简体   繁体   中英

libGDX - make footsteps in a effective way

In a 2D game, that is being developed with libGDX, what is the most effective way to make the footsteps of the player, for example -

if(player.isWalking) {
  Timer.schedule(new Task(){
    public void run(){
      play(single_footstep);
    }
  }, 0.5f);
}

This code isn't effective at all.. actually it's not working, the sound comes in a bad way, and no matter how much you will play with the delay value its still not effective.

BTW - I am using the Timer class of libgdx, which is very similiar to the util one.

So maybe you have a better idea to implement? I am kinda new to libGDX, so maybe I am missing something.

Thanks in advance :)

Is that code simply in your draw loop? If so, it is going to schedule the sound to play every frame, so you'll be starting 30 or 60 sounds a second (each of which is delayed from when you called it, but still played concurrently). You need to make sure that once you schedule the task, you don't do it again until you're ready to play the sound again.

I would do it without scheduling. Something like this:

if (player.isWalking){
    mTimeToNextStep -= deltaTime;
    if (mTimeToNextStep < 0){
        play(single_footstep);
        while (mTimeToNextStep < 0){ //in case of a really slow frame, 
                                    //make sure we don't fall too far behind
            mTimeToNextStep += TIME_BETWEEN_STEP_SOUNDS;
        }
    }
} else {
    mTimeToNextStep = 0; //or whatever delay you want for the first sound when
                         //you start walking
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM