- Home /
CharacterController2D, How does this FixedUpdate() Method actually work?
Can someone explain to me what these lines in FixedUpdate() do/How collision detection works here? especially the if statement: if (colliders[i].gameObject != gameObject). It's a bit from this code https://github.com/Brackeys/2D-Character-Controller
private void FixedUpdate()
{
bool wasGrounded = m_Grounded;
m_Grounded = false;
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
m_Grounded = true;
if (!wasGrounded)
OnLandEvent.Invoke();
}
}
}
Answer by rage_co · Jul 19, 2021 at 04:59 AM
FIxedUpdate() method is a method that runs independent to the frame rate, the code here runs like this
the variable was_grounded is set equal to the value of m_grounded which means that since this code will not run until the next time the method is called, it essentially works as a image of m_grounded's state the last time this method was called (which as the name implies, is called on fixed intervals)
an array of colliders is created using a transform, radius and a layermask, the transform(position) decides where to start the overlap circle (the collider), the radius descibes the radius, and the layermask describes what layers to detect collision with (these can be assigned in the inspector)
A for loop is run, checking the colliders saved and if they are not the colliders of the current gameObject(the player), if this condition is met...m_grounded is set to true and then wasgrounded is checked....if it's false (aka the player was not grounded last time this was run....it runs whatever Events you would like to run upon landing, like a camera bump effect or a landing sound or animation
Hope this helps