Should movement code be inside update() or inside their own functions?

Just a quick question I am wondering.

Currently I have all my movement related code (movement, jumping, running, crouching etc) inside the update function similar in the playcanvas fps movement example. I am wondering if it is best practice to keep all these inside the update function? Or should I put them inside individual functions and then call them individually on the update? Or does it not matter?


It’s mostly a matter of preference. Having a lot of things going on in the update function can make it difficult to sort through for anyone else looking at it, or even you if you don’t visit that script for awhile. As a general rule of thumb you want to keep as little as possible in the actual update function. That being said, especially if you are new to coding, focusing on these types of optimizations can get to be a little discouraging as you start to pour a bunch of time to things that don’t visually or functionally change anything in your game.

At least from a personal standpoint, I would encourage new developers to just get things working first and then optimize afterward.

If I were to do something like an FPS, I would personally have separate functions for the different states of my player and update some sort of variable which changes the specific movement/action script that s called in update. That way if something needed an adjustment, I would know exactly what area of the script I need to look inside of, instead of having to sift through all of the code in update every time I need to change something.


Good question. I think your own preference is the most important here. If you want to do a lot from the update function, creating separate functions can be useful to keep order. Don’t forget to include dt if you want to use delta time in these separate functions.


Noob question but I want to clarify so my understanding is 100%

So when you say you would update some sort of variable which changes the specific movement/action do you mean something like this?

init() {
    // global variables for player states
    this.grounded = false;
    this.jumping = false;

update() {
    if (this.jumping) {
    else {

jump() {
    // jump code

grounded() {
    // grounded code

That’s right! I would check for variables or other information being set the way I want them to be and then calling the specific functions from update based on that information. It just makes it easier to find things later. It can take some time to settle into a flow that you like, but it will be worth it in the end.