- Edited
Hello, I'm new to Godot and wanted to share what took me a couple days to scrape together, but I finally managed to get a working tank controls movement script for version 4.1 for player movement, such as what's used in the classic RE games or Silent Hill. It uses relative positioning to determine where to move and rotate the player.
extends CharacterBody3D
@export var FORWARD_SPEED = 2.0
@export var BACK_SPEED = 1.0
@export var TURN_SPEED = 0.025
var Vec3Z = Vector3.ZERO
#OPTIONAL: These could be used to change sensitivity of either rotating z or y
#var M_LOOK_SENS = 1
#var V_LOOK_SENS = 1
func _physics_process(delta: float) -> void:
if Input.is_action_pressed("move_forward") and Input.is_action_pressed("move_back"):
velocity.x = 0
velocity.z = 0
elif Input.is_action_pressed("move_forward"):
var forwardVector = -Vector3.FORWARD.rotated(Vector3.UP, rotation.y)
velocity = -forwardVector * FORWARD_SPEED
elif Input.is_action_pressed("move_back"):
var backwardVector = Vector3.FORWARD.rotated(Vector3.UP, rotation.y)
velocity = -backwardVector * BACK_SPEED
#If pressing nothing stop velocity
else:
velocity.x = 0
velocity.z = 0
# IF turn left WHILE moving back, turn right
if Input.is_action_pressed("turn_left") and Input.is_action_pressed("move_back"):
rotation.z -= Vec3Z.y + TURN_SPEED #* V_LOOK_SENS
rotation.z = clamp(rotation.x, -50, 90)
rotation.y -= Vec3Z.y + TURN_SPEED #* M_LOOK_SENS
elif Input.is_action_pressed("turn_left"):
rotation.z += Vec3Z.y - TURN_SPEED #* V_LOOK_SENS
rotation.z = clamp(rotation.x, -50, 90)
rotation.y += Vec3Z.y + TURN_SPEED #* M_LOOK_SENS
# IF turn right WHILE moving back, turn left
if Input.is_action_pressed("turn_right") and Input.is_action_pressed("move_back"):
rotation.z += Vec3Z.y - TURN_SPEED #* V_LOOK_SENS
rotation.z = clamp(rotation.x, -50, 90)
rotation.y += Vec3Z.y + TURN_SPEED #* M_LOOK_SENS
elif Input.is_action_pressed("turn_right"):
rotation.z -= Vec3Z.y + TURN_SPEED #* V_LOOK_SENS
rotation.z = clamp(rotation.x, -50, 90)
rotation.y -= Vec3Z.y + TURN_SPEED #* M_LOOK_SENS
move_and_slide()
Hopefully someone can find this helpful!