I am working on a 2d game in unity, and I was wondering how to make the player object shake after contact with an enemy. The shakeFunction works while being called in an Update() function, but not on the collision function.
This is the code that I have:
using UnityEngine;
using System.Collections;
using System.Diagnostics;
public class Shake : MonoBehaviour {
public float shake = 0f;
public float shakeAmount = 0.7f;
public float decreaseFactor = 1.0f;
void OnCollisionEnter2D(Collision2D c)
{
if (c.collider.tag == "Enemy")
{
ShakeFunction();
}
}
}
void ShakeFunction()
{
//Stopwatch timer = new Stopwatch();
//timer.Start();
Vector2 currentPos = gameObject.transform.localPosition;
shake = 5.0f;
//while (timer.Elapsed.TotalSeconds < 3)
//{
if (shake > 0)
{
gameObject.transform.localPosition = currentPos + Random.insideUnitCircle * shakeAmount;
shake -= Time.deltaTime * decreaseFactor;
}
else
{
shake = 0f;
gameObject.transform.localPosition = currentPos;
}
//}
//timer.Stop();
}
}