Hi,
i was wondering how some of you guys manage your player movement in your project.
I always try to use an movement State Enum that includes “IDLE, WALK, RUN, JUMP, DIE, …” and then having a big loop that will check in a switch/case which movement state the player is currently at and then change behaviours according to it.
But sometimes it doesn’t feel good. When i start using it, it works great, but after the player can do more and more things, the code becomes a bit too confusing. For example i have a seperate function that checks if the player is moving (because when i only control movement in the RUN/WALK cycle, and i stop moving to go into IDLE, i would have trouble to see if i am moving again).
But then i would have to ask “if player pressed the movement buttons and is not in movestatement JUMP or DIE or FALLDOWN or HARVESTING or… start moving”. This doesn’t feel right imo.
So i was wondering how do you manage things like this? Do you have a simliar concept or do you do it totally different?
Generally, the smoother and more well animated you want your character to move, the more code you will need to use. In the game I’m making, I use about 20 pages of code just to make a spaceship fly around smoothly and realistically.
Some suggestions I would make for a platformer is to start a new script from scratch. Think of the code you are using now as a rough draft. Coding gets a lot simpler the more you know what you are going to code in the future.
The system of walk/run/jump/ect can defiantly work, but I personally like to code things like this in 3 parts. First, get the controller input, decide how the controller input will affect variables like moving speed, moving direction, vertical speed (aka jump speed). And after applying those variables to the character, determine whether the character is running, jumping, walking, ect. and play the according animation.
I haven’t gotten that far yet, but I would modularize it all. Have simple functions that are called when a key is pressed and then each key would deal with all possibilities.
Ex:
if (key.getInput() = "Jump")
jump();
if (key.getInput() = "Forward")
forward();
...
//Other code for other functions goes here...
...
jump()
{
switch(state)
case "running"
play animation "Running Jump"
case "walking:
play animation "Walking Jump"
case "idle"
play animation "Idle Jump"
...
//Other if's can go here to check other variables if necessary.
//Now make them jump! Add force!
AddForce(vector3.up * jumpSpeed);
}
forward()
{
...
That will be how I attempt to implement my own movement system when the time comes. This of course means if you add a new animation and new input you would have to put the new commands in all functions. That might get messy. I might have to rethink it, but it would work because not all new animations would need to be incorporated into all movements.