I’m trying to have it so that when a ball hits a moving paddle, the paddle gets smaller each time it gets hit on collision.
Right now I have it so that when the bool RightYellowWallMovedBack is true, then it waits 6 seconds to change the x scale of the paddle to 10. THEN, once the ball collides with the paddle, it should change the x scale to 8, and so on and so forth. But it goes directly to the code below it, which is 6. It’s skipping the first collision.
Any ideas?
public IEnumerator paddleScaling()
{
if (Ball8Layer5GreenBall.GetComponent<Ball8Layer5GreenCollide> ().RightYellowWallMovedBack == true)
{
yield return new WaitForSeconds (6);
paddleScale10IsON = true;
this.transform.localScale = new Vector3 (10f, 0.3f, 1f);
}
}
void OnCollisionEnter2D(Collision2D paddleScaleCollider)
{
if (paddleScaleCollider.gameObject.tag == "ball" && paddleScale10IsON == true)
{
this.transform.localScale = new Vector3 (8f, 0.3f, 1f);
paddleScale8IsON = true;
}
if (paddleScaleCollider.gameObject.tag == "ball" && paddleScale8IsON == true)
{
paddleScale6IsON = true;
this.transform.localScale = new Vector3 (6f, 0.3f, 1f);
}
You didn’t post any code that would start the paddleScaling coroutine. So it’s kinda hard to see what you’re doing there.
Anyway… the names in your code are kinda scary. If you have class names or variable names that are the same except for a changing number part, you’re doing something very wrong. Computers are great with numbers and math, so you should use that instead!
Let’s start with your ifs that, I assume, go on for quite a bit after the code you posted. Instead of having lots of boolean variables, why not use a number that indicates the current size? If you look closely, that number already exists - it’s transform.localScale.x. It is always 8 exactly when paddleScale8IsON is true. So you can simply do this:
void OnCollisionEnter2D(Collision2D paddleScaleCollider)
{
if(paddleScaleCollider.gameObject.CompareTag("ball")) // Use CompareTag instead of ==
{
var paddleScale = transform.localScale.x;
if(paddleScale > 2f)
{
paddleScale -= 2f;
}
transform.localScale = new Vector3(paddleScale, 0.3f, 1f);
}
}
and that would be all.
Now, I am not sure if I understood you correctly, but i think you want to do all this only as soon as the Coroutine went through once? in that case, you’d probably want to add a single bool variable:
private bool isScaling = false;
which you set to true at the end of your Coroutine:
yield return new WaitForSeconds (6);
transform.localScale = new Vector3 (10f, 0.3f, 1f);
isScaling = true;
and then you add that to the one if condition of your OnCollisionEnter2D:
You could use Mecanim to animate it. Then you can set perameters to the animation and trigger it through code using animator. SetTrigger, animator.SetBool etc
You could also add some cool effects using Mecanim that would be difficult just in code.