[Bug] Random tweak vector sometimes slows ball

I noticed after some play testing that the tweak vector applied to the rigidbody2D.velocity will occasionally slow the ball down instead of speed it up. This is because it does not take into account the direction the ball is moving during the collision. It always assumes positive x and y direction.

To makes the ball never decelerate you can add a positive/negative modifier to the random tweak vector’s range:

	void OnCollisionEnter2D(Collision2D collision){
		var xDirection = this.rigidbody2D.velocity.x > 0 ? 1 : -1;
		var yDirection = this.rigidbody2D.velocity.y > 0 ? 1 : -1;
		var tweak = new Vector2 (Random.Range (0f, 0.2f) * xDirection, Random.Range (0f, 0.2f) * yDirection);
		this.rigidbody2D.velocity += tweak;
	}

No idea if you’re still there or if anyone else can explain this for me…but can someone please explain the code above? I understand what the expected result is but I don’t really understand how it gets there.

Nevermind. I actually did a bit of digging and found some documentation explaining the parts I didn’t know. I didn’t understand how the ? was used. Also, wasn’t sure about the ‘var’ usage either…still not completely sure, but I just explicitly declared them as ‘int’.

Actually, there’s a completely different issue now…with this code, it will greatly increase the velocity of the ball and I even have it going through objects that it’s not supposed to be able to…hmm…

Privacy & Terms