Hello guys. I am trying to break down the code below (this is similar to breakout etc, where a ball hits the paddle to the left or right of it and gets sort of deflected at a greater angle).
void OnCollisionEnter ( Collision col ) {
foreach (ContactPoint contact in col.contacts ) {
if (contact.thisCollider == collider ) {
//this is the paddle's contact point
float english = contact.point.x - transform.position.x;
contact.otherCollider.rigidbody.AddForce ( 300f * english, 0, 0);
}
}
}
}
So OnCollisionEnter basically initiates when there is a collision between two rigidbodies (in this case the paddle and the ball - this script is applied to the paddle).
( Collision col ) According to the script reference page Unity - Scripting API: MonoBehaviour.OnCollisionEnter(Collision) it says we are passing the class “Collision” and then I guess we are giving it the name col? Can anyone expand on that part and whats going on? Not too familiar with classes in C# (I will read up after promise :P). Does the col part refer to this specific collision?
foreach (ContactPoint contact in col.contacts ) {
I suppose here we use a foreach loop as there may be multiple points of contact? Now I am starting to get confused by the number of “contacts” here… we have ContactPoint contact and contacts
But what do they all refer to?
if (contact.thisCollider == collider ) {
All I know here is that thisCollider refers to the paddle, and it needs to be equal to the “collider” (terms getting a bit vague…).
float english = contact.point.x - transform.position.x;
assigning a floating number variable called english that is result of the calculation “contact.point.x - transform.position.x;” I suppose contact.point.x is the x co-ordinate of the contact point of the collision. But what do we mean here by transform.position.x? I checked this Unity - Scripting API: Collision.transform, is it just “opening up transform” to check the x co-ordinate of the paddle rather than actually transforming something?
contact.otherCollider.rigidbody.AddForce ( 300f * english, 0, 0);
I guess from my previous programming experience we are looking through a bunch of data stuff and then adding more force to the ball (depending on english calculation) but how does more force affect the angle if the ball if its just falling straight down? Or is that stuff taken care of by the physics engine?