Unity中实现苹果手机的Taptic震动

462 阅读1分钟

将上方文件解压之后将MultiHaptic.mm的文件放到Assets/Plugins/iOS目录下,MultiHaptic.cs文件不用挂载到游戏物体上,在需要的时候调用里面的三个静态方法即可

Object-C的代码:

extern "C" {
    
    void _hapticMedium(){
        UIImpactFeedbackGenerator *gen = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleMedium];
        [gen prepare];
        [gen impactOccurred];
    }
    
    void _hapticLight(){
        UIImpactFeedbackGenerator *gen = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleLight];
        [gen prepare];
        [gen impactOccurred];
    }
    
    void _hapticHeavy(){
        UIImpactFeedbackGenerator *gen = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleHeavy];
        [gen prepare];
        [gen impactOccurred];
    }
}

CS的代码:

using UnityEngine;
using System.Runtime.InteropServices;

public class MultHaptic
{
    [DllImport("__Internal")]
    static extern void _hapticMedium();

    [DllImport("__Internal")]
    static extern void _hapticLight();

    [DllImport("__Internal")]
    static extern void _hapticHeavy();

    public static void HapticLight()
    {
        if (Application.platform == RuntimePlatform.IPhonePlayer)
            if (PlayerPrefs.GetInt("Taptic", 1) == 1)
            {
                _hapticLight();
            }
    }

    public static void HapticMedium()
    {
        if (Application.platform == RuntimePlatform.IPhonePlayer)
            if (PlayerPrefs.GetInt("Taptic", 1) == 1)
            {
                _hapticMedium();
            }
    }

    public static void HapticHeavy()
    {
        if (Application.platform == RuntimePlatform.IPhonePlayer)
            if (PlayerPrefs.GetInt("Taptic", 1) == 1)
            {
                _hapticHeavy();
            }
    }
}