godotengine / godot-demo-projects

Demonstration and Template Projects
https://godotengine.org
MIT License
5.83k stars 1.63k forks source link

Mobile Sensors Demo GyroAndGrav rotation inaccurate #988

Open StockerGaming opened 11 months ago

StockerGaming commented 11 months ago

In the demo project "Mobile Sensors Demo" the GyroAndGrav cube is rotated incorrectly when the phone is tilted on its side and then tilted up and down. When you do this, the cube is erroneously also rotates around the real world y axis, which does not correspond to the actual orientation of the phone.

StockerGaming commented 11 months ago

Managed to make a demo without this effect (this works as a script for any Node3D):

var yaw = 0
var old_up

var k : float = 0

func _ready():
    old_up = -1 * Input.get_gravity() 

func _physics_process(delta):
    var up = -1 * Input.get_gravity()
    var angle = up.angle_to(Vector3.UP)
    var axis = up.cross(Vector3.UP).normalized()

    transform.basis = Basis()
    rotate_object_local(axis, angle)

    var gyro = Input.get_gyroscope()
    var x_percentage = transform.basis.x.dot(Vector3.UP)
    var y_percentage = transform.basis.y.dot(Vector3.UP)
    var z_percentage = transform.basis.z.dot(Vector3.UP)

    var up_projected = Vector2(up.x, up.z)
    var old_up_projected = Vector2(old_up.x, old_up.z)

    yaw -= (1 - y_percentage) * up_projected.angle_to(old_up_projected)

    yaw += delta * x_percentage * gyro.x
    yaw += delta * y_percentage * gyro.y
    yaw += delta * z_percentage * gyro.z

    rotate_y(yaw)
    old_up = up
Calinou commented 11 months ago

Which Godot version are you using?

PS: Code blocks should use triple backticks like this (with an optional language name for syntax highlighting):

```gdscript code here ```

I edited your post accordingly, but remember to do this in the future :slightly_smiling_face:

StockerGaming commented 11 months ago

Ah many thanks, was struggling with that. I am using Godot 4.1, sorry for not mentioning that earlier.

StockerGaming commented 11 months ago

Note: This effect happens in the demo too if one comments out the line:

yaw -= (1 - y_percentage) * up_projected.angle_to(old_up_projected)

It is there to combat the incorrect yaw inference made by rotating the basis in an effort to match the y axis to the gravity vector.