Rotate node towards the direction is being moved

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By shackra

In 3D, I’m trying to rotate a node so that it faces where it is being moved, this is what I currently have:

after looking up and down on the internet I cannot find anything that can instruct me how to rotate the node as I want or any code snippet I could use for that matter, the only code that has proven somewhere else to work is the 3D Platformer but oh boy! I don’t understand the math involve on that code!!

the code I have currently in place:

extends KinematicBody

export (float) var speed = 1.5
export (float) var rotation_speed = 0.25
export (float) var ACCELERATION = 2
export (float) var DECELERATION = 4

var velocity = Vector3()

onready var Camera = get_node("../CameraBase/Gimbal/InnerGimbal/Camera")

func _physics_process(delta):
	move(delta)
	move_and_collide(velocity)

func move(delta):
	velocity = Vector3()
	var hspeed = 1
	
	var dir = Vector3()
	dir.x = Input.get_action_strength("mover_este") - Input.get_action_strength("mover_oeste")
	dir.z = Input.get_action_strength("mover_sur") - Input.get_action_strength("mover_norte")
	
	var cam_basis = Camera.global_transform.basis
	var basis = cam_basis.rotated(cam_basis.x, -cam_basis.get_euler().x)
	dir = basis.xform(dir)
	
	# Limit the input to a length of 1. length_squared is faster to check.
	if dir.length_squared() > 1:
		dir /= dir.length()

	# Using only the horizontal velocity, interpolate towards the input.
	var hvel = velocity
	hvel.y = 0

	var target = dir * speed
	var acceleration
	if dir.dot(hvel) > 0:
		acceleration = ACCELERATION
	else:
		acceleration = DECELERATION

	hvel = hvel.linear_interpolate(target, acceleration * delta)

	# Assign hvel's values back to velocity, and then move.
	velocity.x = hvel.x
	velocity.z = hvel.z
	velocity = move_and_slide(velocity, Vector3.UP)
:bust_in_silhouette: Reply From: Adam_S

You could achieve this with the look_at() method. Call it after all values are added to your velocity variable.

if velocity:
    look_at(transform.origin + velocity,Vector3.UP)

But I’m not sure if this is what you want, since this will change the rotation abruptly.

But I’m not sure if this is what you want, since this will change the
rotation abruptly.

for now this is fine, I just used look_at(transform.origin + -velocity, Vector3.UP) instead and the character rotates as expected. Thanks!

shackra | 2020-09-19 17:19