Is there a function which you can check

Is there a function which you can check like
if(gameObject doesnt collide anything for x second){
add Force;
}
Simply this because sometimes ball has really really afwul boring loops which cause cancer for player so I want to change this by adding a random force after a while.

Thank you for your atttention.

You can add a timer by adressing the value of time.time to a float variable at the point that you want to start counting and then compare this variable to time.time under the update method to see if the amount of time that has passed is smaller than the amount of time that you want to make a change if it don’t hit anythinf, whenever you collider with something you can reset the variable to time.time again

So how should I say if not collide something?

if(Ball.GetComponent<Rigidbody2D ().and whatelse) ?

You don’t need a if here, just reset it under the collision method:

OnCollisionEnter2D(collider col)
{
MyCounter = time.time
}

And under the update():
{
if ((time.time - MyCounter) >= timelimit)
{
DoThis();
MyCounter = time.time;
}
}

1 Like

Thank you, made it like that


private float MyCounter;
private float timelimit = 2f;


void Update () {
if ((Time.time - MyCounter) >= timelimit)
{
Vector2 tweak2 = new Vector2(Random.Range(0f, 0.2f), Random.Range(0f, 0.2f));
Ball.GetComponent().velocity += tweak2;
}


void OnCollisionEnter2D(Collision2D collision){
MyCounter = Time.time;
}


So it worked, really appreciate it thanks again.

1 Like

I’m glad that it is working!
Just make sure to reset the counter and to time.time after the if statement too otherwise it will tweak the speed every frame until it hits something.

You can also add one if that make the timer resets only if it hits a brick, just add an

if (collision.tag == BrickTag(string))

By the way, sorry for any wrong spelling of the methods etc. Im on my phone right now so I can’t check

1 Like

Yes as you said now every frame, its getting faster . I tried to reset values but couldnt find which one and where to reset.

I wrote in void OnCollisionEnter2D(Collision2D collision){
if (collision.tag == “Breakable”);
} cannot work either.

this should work:

void OnCollisionEnter2D(Collision2D collision)
{
if (collision.tag == "Breakable")
{
MyCounter = Time.time;
}
}

void Update () { 
if ((Time.time - MyCounter) >= timelimit)
{
Vector2 tweak2 = new Vector2(Random.Range(0f, 0.2f), Random.Range(0f, 0.2f));
Ball.GetComponent().velocity += tweak2;
MyCounter = Time.time;
}

void OnCollisionEnter2D(Collision2D collision)
{
if (collision.tag == "Breakable")
{
MyCounter = Time.time;
}
}

I think the problem is it cannot use collision.tag

try collision.gameObject.tag instead

1 Like

hilarious (Y)

did it worked?

yes it did, thank you for sharing your infos =)

Oh, ok.
Awesome! :slight_smile:

Privacy & Terms