I know that this isn't a problem that is holding me back but, I fear that not understanding my own code could cause problems in the future; I also can't get this topic of my mind right now. So I'm just going to show the movement code and explain why I can't understand it fully.
This is the movement code for my player character:
func movement_code(delta):
var horizontal_velocity = Input.get_vector("move_left","move_right","move_forward","move_backward").normalized() * player.speed
var global_transform_basis = player.global_transform.basis
player.velocity = horizontal_velocity.x * global_transform_basis.x + horizontal_velocity.y * global_transform_basis.z
if player.is_on_floor():
player.velocity_y = 0
if Input.is_action_just_pressed("Jump"):
player.velocity_y = jump_velocity
else:player.velocity_y -= gravity * delta
player.velocity.y = player.velocity_y
player.move_and_slide()
It works well and it does what it supposed to do. I got the code from a Youtube tutorial titled "Godot 4 First-Person Controller with 22 Lines of Code". Here it is:
A challenge that I have had with this code, is when I tried to edit it for enemy AI patrol movement; I just don't know where to start. Now I do have code that works well for the enemy AI patrolling. However, that code wasn't a modification of the player movement code. Instead, this is what I got.
func move_forward():
enemy.position -= enemy.transform.basis.z * speed
enemy.move_and_slide()
The code makes the enemy move forward, while another function makes the enemy turn away from obstracles it detects with the raycast. It works well but, it doesn't involve manipulating the enemy's velocity property while the movement code for the player does involve manipulating the player's velocity property.
Everytime when I try to get the enemy to move by manipulating it's velocity property, I don't seem to get the results I want; this is probably indicative of my ignorance regarding how the player movement code works or how the velocity property works in Godot 4.
The documentation says that velocity is a Vector3 for CharacterBody3D nodes. However, my enemy wouldn't move at all if I were to make the code like this:
func move_forward():
enemy.velocity.z += 5
enemy.move_and_slide()
I'm not sure if anything I'm saying here even makes any sense to anyone else. Could anyone explain to me what is going on?