Browse Source

:wrench: Make walker controllable

DricomDragon 1 year ago
parent
commit
9be0e57bae

+ 37 - 0
first3d/component/entity/walker/walker.gd

@@ -0,0 +1,37 @@
+class_name Walker
+extends CharacterBody3D
+
+# How fast the player moves in meters per second.
+@export var speed = 14
+# The downward acceleration when in the air, in meters per second squared.
+@export var fall_acceleration = 75
+
+var target_velocity = Vector3.ZERO
+
+
+func _physics_process(delta: float) -> void:
+	var direction = Vector3.ZERO
+
+	if Input.is_action_pressed("move_right"):
+		direction.x += 1
+	if Input.is_action_pressed("move_left"):
+		direction.x -= 1
+	if Input.is_action_pressed("move_back"):
+		direction.z += 1
+	if Input.is_action_pressed("move_forward"):
+		direction.z -= 1
+
+	if direction != Vector3.ZERO:
+		direction = direction.normalized()
+
+	# Ground Velocity
+	target_velocity.x = direction.x * speed
+	target_velocity.z = direction.z * speed
+
+	# Vertical Velocity
+	if not is_on_floor(): # If in the air, fall towards the floor. Literally gravity
+		target_velocity.y = target_velocity.y - (fall_acceleration * delta)
+
+	# Moving the Character
+	velocity = target_velocity
+	move_and_slide()

+ 4 - 1
first3d/component/entity/walker/walker.tscn

@@ -1,4 +1,6 @@
-[gd_scene load_steps=3 format=3 uid="uid://b10k58capm04o"]
+[gd_scene load_steps=4 format=3 uid="uid://b10k58capm04o"]
+
+[ext_resource type="Script" path="res://component/entity/walker/walker.gd" id="1_xg6by"]
 
 [sub_resource type="CapsuleMesh" id="CapsuleMesh_skhap"]
 radial_segments = 8
@@ -7,6 +9,7 @@ rings = 4
 [sub_resource type="CapsuleShape3D" id="CapsuleShape3D_4r1ky"]
 
 [node name="Walker" type="CharacterBody3D"]
+script = ExtResource("1_xg6by")
 
 [node name="Skin" type="MeshInstance3D" parent="."]
 mesh = SubResource("CapsuleMesh_skhap")