Align rotation with Vector

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Löwenhügel
:warning: Old Version Published before Godot 3 was released.

I’ve got an object whose y-axis I want to align with a directional Vector3 while not manipulating the rotation around the y-axis itself. Is there any (simple) way to do this?
Additionally, it would be nice to change the rotation over some time, but that’s secondary.

:bust_in_silhouette: Reply From: metin

I’m not sure what exactly you want to do but I guess you already checked out the look_at() function but it’s not what you need? You can set any rotation by manipulating the basis of your object. Make your directional Vector3 normalized and use it as your basis.y. Then calculate basis.x and basis.z so that you get the orientation that you want. Make sure that all three vectors are normalized and rectangular to each other.
To make the rotation over time you should use a Quaternion with slerp().

I can show you a code snippet from me, maybe it gives you some inspiration. I use it to rotate a tank turret around 1 axis towards a target in 3D space. The turret sits on a moving chassis.

var chassis_transform = get_parent().get_global_transform()
var turret_transform = get_global_transform()

# vector for rotation axis of turret
var turret_up = chassis_transform.basis.y.normalized()

# plane trough turret
var p1 = turret_transform.origin
var p2 = p1 + turret_transform.basis.x
var p3 = p1 + turret_transform.basis.z

var plane = Plane(p1, p2, p3)
look_at = plane.project(global.cursor_pos_3d)
if(typeof(look_at) == TYPE_VECTOR3):
	var x = (look_at - turret_transform.origin).normalized()
	var y = turret_up.normalized()
	var z = x.cross(y).normalized()
	var quaternion_current = Quat(turret_transform.basis)
	var quaternion_new = quaternion_current.slerp(Matrix3(x, y, z), dt*3.0)
	set_global_transform(Transform(quaternion_new, turret_transform.origin))

That’s not exactly what I wanted, but thank you anyway. I figured out the solution to my original quation on my own: rotate(Vector3.cross(get_transform().basis.y).normalized(),get_transform().basis.y.angle_to(Vector3))
Maybe now it’s understandable what I tried to do.

Löwenhügel | 2017-09-02 18:12

How to x and z Align rotation?

Lightnet | 2018-02-11 11:38

:bust_in_silhouette: Reply From: Löwenhügel

rotate(Vector3.cross(get_transform().basis.y).normalized(),get_transform().basis.y.angle_to(Vector3))
For all the people having the same problem