Here are a few steps:
-STEP 1: test it
dial *#0*# (be patient, it might take a few seconds)
go to "sensors"
click on "gyro selfstest" under "gyroscope sensor"
If result is "fail", proceed with step 2
-STEP 2: boot in safe mode
just watch this video, as seeing it will be easier to understand than me explaining it
https://youtu.be/BvJYYKaWmNc
Full credits to OP of that video.
-STEP 3: repeat step 1
don't worry if it's still a fail.
-STEP 4: repeat step 1 (again)
it should be a "pass" now. If it isn't, it might be a hardware problem. Then you might need a new phone
try it out on various apps