Making an Android phone vibrate for 100ms C#

不羁的心 提交于 2021-02-08 05:04:40

问题


I've been trying out a few games on my phone in the last week, and saw that some used vibration as a "feedback" for the player when something happened, like:

  • The player crashed into a wall;
  • The player did a perfect launch;
  • The player received a big prize...

and so on...

I really love how giving a little vibration or small shake to the phone, can basically tell the player that something important (for the game) happened, through an output that isn't only on the screen or comes from the speaker.

I'm developing my game with Unity.

In my game, I would make the phone vibrate when the player crashes, and when he receives a big prize, like I've seen other beautiful games doing.

I've already tried using the default vibration: Handheld.Vibrate(), that worked, but it was lasting for too much time for my need and I wouldn't have been able to change anything in it.

I've read that, to do this, I would need to write a separate plugin, or use one that already exists. I have not found any working ones, and have no idea how to write one!

I would only need to call something like vibrateFor(100) where 100 are the milliseconds.

Some games, like "Perfect Slices" seem to use this a lot.

So, can anyone make such a plugin for me or point out an existing one for Android?

Thanks for your help in advance!

Edit: Otherwise, could anyone explain to me in detail how to use this plugin that seems to have worked for other people?

Unity version is 2019.2.8f1.


回答1:


Since version 2018.3 Unity allows you to add .java files into your Unity Project and they are compiled when you build an Android player.

1) Copy the output UnityAndroidVibrator.java and AndroidManifest.xml files into the Assets/Plugins/Android directory in your Unity project.

2) Go to: [File] > [build Settings] > [Player Settings] > [Player] and copy package name.

3) In both classes find and replace "uav.uav.uav" package name with that you copied in step 2).


UnityAndroidVibrator.cs class:

using UnityEngine;
public class UnityAndroidVibrator : MonoBehaviour 
{
    #if UNITY_ANDROID || UNITY_EDITOR 
    private static AndroidJavaObject plugin = null;
    #endif


    // Use this for initialization
    void Awake () 
    {
        #if UNITY_ANDROID && !UNITY_EDITOR 
        plugin = new AndroidJavaClass("uav.uav.uav.UnityAndroidVibrator").CallStatic<AndroidJavaObject>("instance");
        #endif
    }


    /// <summary>
    /// <para>Vibrates For Given Amount Of Time.</para>
    /// <para>1 sec = 1000 Millseconds :)</para>
    /// </summary>
    /// <param name="DurationInMilliseconds">Duration in milliseconds.</param>
    public void VibrateForGivenDuration(int DurationInMilliseconds)
    {
        plugin.Call("VibrateForGivenDuration", DurationInMilliseconds);

    }

    /// <summary>
    /// Stoping All Vibrate.
    /// </summary>
    public void StopVibrate()
    {
        plugin.Call("StopVibrate");
    }


    /// <summary>
    /// <para>Customs Vibrate or Vibration with Pattern.</para>
    /// <para>Start without a delay</para>
    /// <para>Each element then alternates between vibrate, sleep, vibrate, sleep...</para>
    /// <para>long[] Pattern = {0, 100, 100, 300};</para>
    /// </summary>
    /// <param name="Pattern">Pattern.</param>
    public void CustomVibrate(long[] Pattern)
    {
        plugin.Call("CustomVibrate", Pattern);
    }


}

UnityAndroidVibrator.java class:

package uav.uav.uav;

import android.os.Vibrator;
import com.unity3d.player.UnityPlayer;

public class UnityAndroidVibrator 
{
    private static UnityAndroidVibrator _instance;

    public UnityAndroidVibrator() {
    }

    public void VibrateForGivenDuration(int duration) {
        Vibrator vibs = (Vibrator)UnityPlayer.currentActivity.getApplicationContext().getSystemService("vibrator");
        vibs.vibrate((long)duration);
    }

    public void StopVibrate() {
        Vibrator vibs = (Vibrator)UnityPlayer.currentActivity.getApplicationContext().getSystemService("vibrator");
        vibs.cancel();
    }

    public void CustomVibrate(long[] Pattern) {
        Vibrator vibs = (Vibrator)UnityPlayer.currentActivity.getApplicationContext().getSystemService("vibrator");
        vibs.vibrate(Pattern, -1);
    }

    public static UnityAndroidVibrator instance() 
    {
        if (_instance == null) 
        {
            _instance = new UnityAndroidVibrator();
        }

        return _instance;
    }
}

AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.unity3d.player" xmlns:tools="http://schemas.android.com/tools">
  <application>
    <activity android:name="com.unity3d.player.UnityPlayerActivity" android:theme="@style/UnityThemeSelector" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
  <uses-permission android:name="android.permission.VIBRATE" />
</manifest>

Note: for example if your package name is "com.my.app" the resulting name would be:

"UnityAndroidVibrator.cs" class:

plugin = new AndroidJavaClass("com.my.app.UnityAndroidVibrator").CallStatic<AndroidJavaObject>("instance");

"UnityAndroidVibrator.java" class:

package com.my.app;

import android.os.Vibrator;
import com.unity3d.player.UnityPlayer;



回答2:


I'm a Xamarin developer not Unity but I believe that even outside of Xamarin projects you can reference the Xamarin.Essentials library - it's then as simple as calling

Xamarin.Essentials.Vibration.Vibrate(100);

When you want it to happen

On Android you have to add the vibration permission to the android manifest file. I'm not sure how to do this on unity but on xamarin you just add the line

<uses-permission android:name="android.permission.VIBRATE" />

to the manifest xml, it might be the same on Unity.

https://www.nuget.org/packages/Xamarin.Essentials/

https://docs.microsoft.com/en-us/xamarin/essentials/vibrate?tabs=android



来源:https://stackoverflow.com/questions/59123343/making-an-android-phone-vibrate-for-100ms-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!