- Home /
How to shake a spinning object?
Hello everyone, I have an object which I spin it by swipe input and I want to shake it when I've tapped. In my last attempt I could shake it but it doesn't carry the torque so it seems weird. Also I want it to get back in position smoothly, I have tried Lerp and Slerp but can't make it work. Any suggestions?
public class PlatformController : MonoBehaviour
{
[SerializeField]
private float rotationForce = 10f;
private Vector3 firstTouch, lastTouch, touchDeltaPosition;
private Touch touch;
private bool shaking = false;
void Update()
{
//If player touches the screen
if(Input.touchCount > 0)
{
//Starting the touch pase
touch = Input.GetTouch(0);
switch (touch.phase)
{
case TouchPhase.Began:
firstTouch = touch.position;
break;
case TouchPhase.Ended:
lastTouch = touch.position;
//Detecting if its tap or swipe
if(firstTouch == lastTouch)
{
//Calling the "not working" shake method
ShakeMe();
Debug.Log("Tapped");
}
if (firstTouch != lastTouch)
{
touchDeltaPosition = firstTouch - lastTouch;
GetComponent<Rigidbody>().AddRelativeTorque(0, touchDeltaPosition.x * rotationForce, 0);
}
break;
}
}
if (shaking)
{
transform.rotation = Quaternion.Euler(-10, 0, 0);
}
}
public void ShakeMe()
{
StartCoroutine("ShakeNow");
}
IEnumerator ShakeNow()
{
//Tried different things for return the cylinder to its original position but not succeded
Quaternion originalRotation = transform.rotation;
if (shaking == false)
{
shaking = true;
}
yield return new WaitForSeconds(0.2f);
shaking = false;
transform.rotation = originalRotation;
//transform.rotation = Quaternion.Lerp(transform.rotation, originalRotation, Time.deltaTime * 0.1f);
}
}
Not the opportunity to look deeper into your code right now, but here's a suggestion how I would attempt this: I would create a parent Gameobject, which holds your rotating Gameobject. Then shake that parent gameobject. I would also write a seperate script for the shaking. This makes it easier to debug and makes it possible to use elsewhere as well.
Also, I notice that you use a string to call your Coroutine StartCoroutine("ShakeNow");
. This is no good if you ever change the name of your Coroutine, then you lose the reference. Instead call it like a function, like so: StartCoroutine(ShakeNow());
Really appreciate it, I will give it a shot and share the results. Also thanks for the tip. Cheers!
Your answer
Follow this Question
Related Questions
Earth quake with physics? 1 Answer
Camera is shaking. Unity 3D 0 Answers
Shake Effect 0 Answers
Moving sphere tremble in moving camera view[Solved] 0 Answers
How to make a gamebject wiggle slowly as it moves forward ? 1 Answer