Hello, I’m currently working on a line-runner style game and have tried adding haptic feedback; however, when trying to do so, I have been unsuccessful and haven’t found many posts about it on the forums and the documentation didn’t help a lot.
My game uses a custom camera system so I decided to try and link the vibrations to the magnitude of any camera shake effects. This is a sample of the code for mobile and controllers:
local Offset = Humanoid.CameraOffset
local Magnitude = Offset.Magnitude
if UserInputService.TouchEnabled == true then
HapticService:SetMotor(Enum.UserInputType.Touch, Enum.VibrationMotor.Small, Magnitude)
elseif UserInputService.GamepadEnabled == true then
HapticService:SetMotor(Enum.UserInputType.Gamepad1, Enum.VibrationMotor.RightTrigger, Magnitude)
end
I was able to test this code on a PS5 controller and an iphone 11; however, I was unable to experience any haptic vibrations even after trying alternative values.
The only posts I was able to find on the matter was a feature request for haptic vibrations and news that the API was being reworked a few years ago.
I tried copying the code from this un-copylocked place; however, for some reason, it didn’t work in my game when I copied it over despite it working on the same iPhone 11 in the original game and me not changing any of the code.
This was the code that I copied:
local hapticService = game:GetService('HapticService')
local CAN_VIBRATE = hapticService:IsMotorSupported(Enum.UserInputType.Gamepad1, Enum.VibrationMotor.Small) -- phones use Gamepad1, probably as a placeholder but not sure if they're actually adding a mobile enum
if CAN_VIBRATE then -- if the device can vibrate
local lastTap
local VIBRATION_LENGTH = 1 / 60
script.Parent.MouseButton1Click:Connect(function()
local thisTick = tick() -- we need to save the time the user clicked in order to not have weird behaviour with vibration length, this is especially apparent with long vibration lengths
lastTap = thisTick
hapticService:SetMotor(Enum.UserInputType.Gamepad1, Enum.VibrationMotor.Small, 1)
task.wait(VIBRATION_LENGTH)
if lastTap == thisTick then -- now we check that the last input that was made was this event, if it was, it's safe to stop vibrating
hapticService:SetMotor(Enum.UserInputType.Gamepad1, Enum.VibrationMotor.Small, 0)
end
end)
end
(The code was located inside a text button so I also placed it inside one)
While testing, I have found that the IsMotorSupported
function returns true when tested on the iPhone; however, the SetMotor
function only works in the older experience. Furthermore, I have also been unable to get it to work on the PS5 controller I have used test the feature with for consoles.
(I am using the controller with a PC and not a PS5 if that is relevant)
I am hesitant to post a bug report as I am unsure if it is a mistake on my behalf.
If anyone knows how I can use this feature, please let me know.
Thanks for reading!
Have a good day