Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | jon4short |
Hi There,
In my 3D project, I want to move the character around just with WASD like in Overcooked and Animal Crossing. This is the script I have so far. But the character rotation just jumps to each direction instead of turning smoothly.
extends KinematicBody
var gravity = -9.8
var velocity = Vector3()
var camera
var character
const SPEED = 6
const ACCELERATION = 3
const DECEL = 5
func _ready():
camera = get_node("../Camera").get_global_transform()
character = get_node(".")
#func _process(delta):
func _physics_process(delta):
var dir = Vector3()
var is_moving = false
if(Input.is_action_pressed("move_forward")):
dir += -camera.basis[2]
is_moving = true
if(Input.is_action_pressed("move_back")):
dir += camera.basis[2]
is_moving = true
if(Input.is_action_pressed("strafe_left")):
dir += -camera.basis[0]
is_moving = true
if(Input.is_action_pressed("strafe_right")):
dir += camera.basis[0]
is_moving = true
dir.y = 0
dir = dir.normalized()
velocity.y += delta * gravity
var hv = velocity
hv.y = 0
var new_pos = dir * SPEED
var accel = DECEL
if (dir.dot(hv) > 0):
accel = ACCELERATION
hv = hv.linear_interpolate(new_pos, accel * delta)
velocity.x = hv.x
velocity.z = hv.z
velocity = move_and_slide(velocity, Vector3(0,1,0))
if is_moving:
# Rotates the player to direction moving
var angle = -atan2(hv.x, -hv.z)
var char_rot = character.get_rotation()
char_rot.y = angle
character.set_rotation(char_rot)