Reputation: 711
I would like to use my circlecollider2d as a sort of force field to push objects back for a given amount of time, on button press. Here is the code I have, to simply turn it on and off again.
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
GetComponent<CircleCollider2D>().radius = 25.0f;
}
else
{
GetComponent<CircleCollider2D>().radius = 2.1f;
}
}
Upvotes: 1
Views: 254
Reputation: 7185
You can use Invoke
to call a function after x number of seconds. I modified your code below to clear the force field 5 seconds after it is activated. The forceFieldActive
flag will prevent it from being activated again while it's already active.
int forceFieldDuration = 5; //5 second duration
bool forceFieldActive = false;
void Update()
{
if (Input.GetKey(KeyCode.Space) && forceFieldActive == false)
{
forceFieldActive = true;
GetComponent<CircleCollider2D>().radius = 25.0f;
Invoke("DisableForceField", 5);
}
}
void DisableForceField()
{
GetComponent<CircleCollider2D>().radius = 2.1f;
forceFieldActive = false;
}
Note: You can also use a coroutine which is more efficient as Draco18s mentioned in the comments. It would look like this:
int forceFieldDuration = 5; //5 second duration
bool forceFieldActive = false;
void Update()
{
if (Input.GetKey(KeyCode.Space) && forceFieldActive == false)
{
forceFieldActive = true;
GetComponent<CircleCollider2D>().radius = 25.0f;
StartCoroutine(DisableForceField());
}
}
IEnumerator DisableForceField()
{
yield return new WaitForSeconds(forceFieldDuration);
GetComponent<CircleCollider2D>().radius = 2.1f;
forceFieldActive = false;
}
Upvotes: 3