Unity Platform 01 Gravity Setting / Wall overlap === 2020.08.05 ###### tags: `platform` ## Object 1. Custom script-driven physics for 2D 2. Horizontal movement & cancelable jump 3. Sloped and angled surfaces collision ## LIST 1. [Default Gravity](#SG) 1. [deltaTime](#delta) 2. [Default Setting](#default) 2. [Collision with grounded](#collision) 1. [Check Overlap](#overlap) 2. [ContactFilter2D](#filter) <br><br> ## CONTENT ### Defualt Gravity<a id="SG"/> #### deltaTime<a id="delta"/> `Time.deltaTime` is frame time before. It use for correct time duration with physics moving. <br><br> ### Defuault Setting<a id="default"/> ```csharp= using UnityEngine; using System.Collections; using System.Collections.Generic; public class PhysicsObj : MonoBehaviour { public float gravityModifier = 1f; protected Rigidbody2D rb2D; protected Vector2 velocity; private void Start() { rb2D = GetComponent<Rigidbody2D>(); } private void FixedUpdate() { velocity += gravityModifier * Physics2D.gravity * Time.deltaTime; Vector2 deltaPosition = velocity * Time.deltaTime; Vector2 move = Vector2.up * deltaPosition.y; Movement(move); } protected void Movement(Vector2 move) { rb2D.position += move; } } ``` <br><br> ### Collision with Ground<a id="collision"/> #### Check Overlap<a id="overlap"/> Overlapping objects are found by casting.<br>Casting is collision check with line and collision space.<br> ```csharp= int count = rb2D.Cast(move, contactFilter, hitBuffer, distance + shellRaius); hitBufferList.Clear(); for (int i = 0; i < count; i++) { hitBufferList.Add(hitBuffer[i]); } ``` <br><br> #### ContactFilter2D<a id="filter"/> ContactFilter2D for collision filtering using layerMask, depth, etc...<br>If you want to use layermask, write below ```csharp= contactFilter.useTriggers = false; contactFilter.SetLayerMask(Physics2D.GetLayerCollisionMask(gameObject.layer)); contactFilter.useLayerMask = true; ``` Filtering layer option set on `"Project Setting" - "Physics2D".` <br><br> #### ground check(with slide line) Use `List<RayCastHit2D>` and each normal for ground check.<br>RayCastHit list is composed of all collision objs<br>If normal is greater than minValue, it is ground<br>And if we move to y pos direction, calculate velocity with normal value.<br><br> ```csharp= for (int i = 0; i< hitBufferList.Count; i++) { Vector2 currentNormal = hitBufferList[i].normal; if (currentNormal.y > minGroundNormalY) { grounded = true; if (yMovement) { groundedNormal = currentNormal; currentNormal.x = 0; } } float projection = Vector2.Dot(velocity, currentNormal); // descnedanct velocity if (projection < 0) { velocity = velocity - projection * currentNormal; } // Collision distance low and real move, back it float modifiedDistance = hitBufferList[i].distance - shellRaius; distance = modifiedDistance < distance ? modifiedDistance : distance; } ``` Projection is rate loss speed with current force(velocity) and groundupVector(groundNormal)