Okay. Let's start there. This example is in 2D, but it still has its uses.
extends KinematicBody2D
export (int) var speed = 200
var velocity = Vector2()
func get_input():
velocity = Vector2()
if Input.is_action_pressed("right"):
velocity.x += 1
if Input.is_action_pressed("left"):
velocity.x -= 1
if Input.is_action_pressed("down"):
velocity.y += 1
if Input.is_action_pressed("up"):
velocity.y -= 1
velocity = velocity.normalized() * speed
func _physics_process(delta):
get_input()
velocity = move_and_slide(velocity)
It's the code off of the Godot docs, but what is it doing?
First off, the kinematicBody2D is what the player character is, obviously. It's the node used for the player.
Now, export (int) var speed = 200. Export is telling Godot to show the variable speed in the editor, and (int) is specifying what variable speed is. Without (int) or whatever the variable type is in parentheses after Export, it will not work and throw an error. The code would think speed could be anything, so it doesn't know what to put in the variable.
Okay, moving on.velocity = Vector2(). This is saying Vector2(0, 0). Why do we need that? Let's say you wrote out this entire code, and then deleted this part. What happens? Simple answer- once the player starts moving, without this line of code, it will not stop.
Input.is_action_pressed("right"):. All this is doing is checking if the input for right is being pressed. However, "right" is not a pre-built input. For beginners, I encourage you to actually use ui_right instead, even though this input is actually meant to be used for UI. The reason I actually like this is because, it's easier to use pre-built inputs over making your own. If you're just starting out, you don't have a clue on what anything does yet.
velocity.x += 1. What do these codes that say velocity.x and y -= or += y? This is telling velocity(0,0) to change. Why?
in physics process, velocity is actually the speed which your character is moving. It will add or subtract 1 from its original position to simulate movement. If you remove velocity = move_and_slide(velocity), the player will not move at all.
Now, go up just a little bit. What is normalized? If you go left, you move to -1,0. If you go up, it's 0, -1. if you go left-up, it's -1,-1. This means your character moves very quickly in diagonals. normalized() keeps the diagonal movement from moving so fast. Then multiply velocity * speed to make the character move in a direction based on a speed, so now velocity is actually -200,0 when you move left. Now remember, export (int) speed = 200 can also be changed in the inspector. Whatever number you put there will override the coded out speed.
As this was actually in 2D, these same principles can work for 3D, ie velocity = Vector3(), and then, based on the direction you need to go, you can change the x, y, and z coordinates. so velocity.x += whatever, or velocity.y += whatever, and velocity.z += whatever.