Don't know why checking if not something stops the whole thing working

Hello :slight_smile:

context… 2D… script is on a block, currently on a Z rotation of 90 (vertical). The projectile hits it (it’s recording x & y velocities from the projectile around 6-7 each on test), the block is destroyed & the projectile disappears. This all works fine if I don’t check for !vert, ie if the block is horizontal, which it could be, but isn’t at the moment.
The idea being that the projectile needs to have some sort of velocity heading towards the block to destroy it.

here is the code:

public class Breakable : MonoBehaviour {

	public bool vert;
	public float xVel;
	public float yVel;

	void Start ()
	{
		if (this.transform.rotation.eulerAngles.z <45f)
			vert = false;
		else
			vert = true;
	}


	void OnCollisionEnter2D (Collision2D coll)
	{
		if (coll.gameObject.tag == "Projectile")
			xVel = coll.gameObject.rigidbody2D.velocity.x;
			yVel = coll.gameObject.rigidbody2D.velocity.y;

			if (vert && xVel > 1f)
				{
					coll.gameObject.SetActive (false);
					Destroy (this.gameObject);
				}
			
			else if (!vert && yVel > 1f)
				{
					coll.gameObject.SetActive (false);
					Destroy (this.gameObject);
				}
				
	}
}

it works if I don’t check vertical at all & it works if I check it is vertical both times, but it doesn’t work if I check it is not vertical anywhere… any idea why & how I can fix it?

Stuff is public just so I can see it while in play.

Further to the above… I have tried changing one of the blocks with this script on to a z rotation of 0, so that it counts as horizontal (!vert).
I took out the !vert from the else.

The script will destroy the vertical block, but does not record a yVel on the horizontal block…but checking the projectile in play it does have quite a bit of y movement at the time it hits. So now I am more confused.

I’m not sure what you actually want to do, but let me fix your indention and you might see your problem:

void OnCollisionEnter2D (Collision2D coll)
{
    if (coll.gameObject.tag == "Projectile")
        xVel = coll.gameObject.rigidbody2D.velocity.x;

    yVel = coll.gameObject.rigidbody2D.velocity.y;

    if (vert && xVel > 1f)
    {
        coll.gameObject.SetActive (false);
        Destroy (this.gameObject);
    }
    else if (!vert && yVel > 1f)
    {
        coll.gameObject.SetActive (false);
        Destroy (this.gameObject);
    }
}

As you can see the first “tag”-condition only covers the xVel assignment. You probably want to enclose the whole thing in brackets {}