Rotation using transform.basis and a joystick

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

How would I set the rotation of my joystick to a vector 3 and rotate my player towards it (only the y-axis) using slerp? (this is a 3d game)

:bust_in_silhouette: Reply From: wombatstampede

I saw some joystick-related code in this example:

This is some untested code, which hopefully helps:

const JOYPAD_DEADZONE = 0.15
const FOLLOW_SECS = 0.5

_physics_process(delta):
  var joypad_vec = Vector2()
  if Input.get_connected_joypads().size() > 0:
    joypad_vec = Vector2(Input.get_joy_axis(0, 2),Input.get_joy_axis(0, 3))
    if joypad_vec.length()>JOYPAD_DEADZONE:
      joypad_vec=joypad_vec.normalized()
      var current_vec=Vector2(Basis.x,Basis.z)
      Basis=Basis.slerp(Basis.rotated(Vector3(0,1,0),current_vec.angle_to(joypad_vec)),delta/FOLLOW_SECS)

This code first gets the joystick coords and puts them into x,y of a vector2.
You might have to adjust the axis-values depending on the joystick and axes you use.
If the values are not too close to the center (DEADZONE) then that vector is normalized (set to length 1).
You also might have to multiply the z-value with -1. This depends on where “forward” is on your mesh.

One way is now to create a rotated basis. The angle of rotation is determined by using the vector2 method “angle_to” which determines the smallest angle between basis.z (current_vec) and the joystick “vector”. I chose the Vector2.angle_to() because this hopefully returns a signed angle (opposed to Vector3()). (See here: Vector3::angle_to() does not return a signed angle · Issue #31519 · godotengine/godot · GitHub )

The slerp value is determined by the time which you allow to reach the joystick angle. FOLLOW_SECS should be that time in seconds. (So if you hold the joystick steady in one direction, the basis should be rotated in that direction after 0.5 secs)

Code may contain errors. But I hope that it runs in general.