How do you detect shakes in Unity? Simple! In this tutorial you will learn how to do it by creating a simple shaking game.
ShakeDetector.cs
using UnityEngine; [RequireComponent(typeof(PhysicsController))] public class ShakeDetector : MonoBehaviour { public float ShakeDetectionThreshold; public float MinShakeInterval; private float sqrShakeDetectionThreshold; private float timeSinceLastShake; private PhysicsController physicsController; void Start () { sqrShakeDetectionThreshold = Mathf.Pow(ShakeDetectionThreshold, 2); physicsController = GetComponent<PhysicsController>(); } void Update () { if (Input.acceleration.sqrMagnitude >= sqrShakeDetectionThreshold && Time.unscaledTime >= timeSinceLastShake + MinShakeInterval) { physicsController.ShakeRigidbodies(Input.acceleration); timeSinceLastShake = Time.unscaledTime; } } }
PhysicsController.cs
using UnityEngine; public class PhysicsController : MonoBehaviour { public float ShakeForceMultiplier; public Rigidbody2D[] ShakingRigidbodies; public void ShakeRigidbodies(Vector3 deviceAcceleration) { foreach (var rigidbody in ShakingRigidbodies) { rigidbody.AddForce(deviceAcceleration * ShakeForceMultiplier, ForceMode2D.Impulse); } } }
awesome, thank you