I’m trying to make a jackhammer with a rock. I currently have this script. The problem I’m having is that the variable, rockhits, starts going up after the jackhammer stops colliding with the rock. What I’m trying to do is whenever the jackhammer is colliding with the rock, the variable rockhits goes up, and whenever the jackhammer stops colliding the variable stops going up. Here’s my script right now:
var collision = false;
var rockhits = 0;
function OnTriggerEnter(col: Collider)
{
if (col.transform.tag == "Rocks")
{
collision = true;
}
else
collision = false;
while (collision == true)
{
rockhits++;
if (rockhits == 10)
{
rocks.renderer.enabled = false;
}
yield WaitForSeconds(0.5);
}
}
I know the colliding part works, I’ve tested that. I can’t figure out why the other parts don’t work.
EDIT:
How come I have to completely put the jackhammer into the rock for it to detect it? (Obviously the collider is set to “is trigger” which is why I can stick it through in the first place)
Look at OnCollisionExit and OnCollisionStay. Probably the latter for you. Or you can increment that count in an Update function, if you use a boolean to indicate that it has ‘entered’ (in On…Enter) and ‘un-entered’ (in On…Exit).
You may want to look into putting your while loop into its own method that is called by OnTriggerEnter for more control, but more likely look at using OnTriggerStay().
You don’t need this to be a trigger. You could make this a collider. There is an analagous OnCollider family (no urls this time) that behaves very similarly. You can make the collider solid and OnCollisionEnter flag true and OnCollisionExit flag false, or try OnCollisionStay to increment your count.
My only words of caution would be you might want a time counter rather than a hit counter as you’d be getting hits per frame and this is unreliable. If you had OnCollisionStay increment a counter by Time.deltaTime and if the counter was greater than the time threshold, kill the rock, this might be more accurate.
Lastly, you will need some way of detecting which rock you are breaking, so there would need to be either an id per rock and a list or array of rocks being broken, or the rock itself should carry the counter so he rock knows and holds its own damage.