Godot Version
godot 4
Player code
extends CharacterBody3D
const SPEED = 5.0
const JUMP_VELOCITY = 2.75
Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting(“physics/3d/default_gravity”)
Sensitivity for mouse rotation
var mouse_sensitivity = 0.3
Mouse rotation variables
var yaw = 0.0
var pitch = 0.0
var bullet = load(“res://bullet.tscn”) # Corrected the path here
@onready var gun_anim = $glock19/AnimationPlayer
@onready var gun_barrel = $glock19/RayCast3D
func _ready():
Input.mouse_mode = Input.MOUSE_MODE_HIDDEN
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y -= gravity * delta
# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var input_dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
if direction:
velocity.x = direction.x * SPEED
velocity.z = direction.z * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
velocity.z = move_toward(velocity.z, 0, SPEED)
# Check for mouse button press to fire the projectile
if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
fireprojectile()
move_and_slide()
func _input(event):
if event is InputEventMouseMotion:
yaw -= event.relative.x * mouse_sensitivity
pitch -= event.relative.y * mouse_sensitivity
pitch = clamp(pitch, -90, 90)
$Camera3D.rotation_degrees.x = pitch
rotation_degrees.y = yaw
if Input.is_action_just_pressed("pause"):
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
func input(event):
if event.is_action_pressed(“fullscreen”):
DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN)
func fireprojectile():
if !gun_anim.is_playing():
gun_anim.play(“Shoot”)
# Instantiate the projectile
var instance = bullet.instantiate()
# Set the position
instance.position = gun_barrel.global_position
# Set the direction based on the gun barrel's forward direction
var direction = -gun_barrel.global_transform.basis.z.normalized()
instance.direction = direction
# Add the instance to the scene
get_tree().root.add_child(instance)
Projectile code
extends Node3D
const SPEED = 40
@onready var mesh = $MeshInstance3D
@onready var ray = $RayCast3D
var direction = Vector3(0, 0, -1) # Default forward direction
func _ready():
# This function will be called when the projectile is instantiated
# If you want to set the direction based on some initial setup, do it here
pass
func _process(delta):
# Move the projectile in the direction it is facing
var movement = direction * SPEED * delta
position += movement