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
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Your article helped me a lot, is there any more related content? Thanks!
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?