Colliders overlapping

I feel like this question MUST have been answered somewhere before but after a few hours of research I can’t find anything so, here I am!

Just starting out, I am just doing some experimenting on how to get collision detection in a game to work properly. I have two objects in my world, both with box colliders, arranged in a vertical line. The upper collider is a Rigidbody and at startup, I assign it a velocity straight down with a speed of 1. It falls until it hits the lower object and then stops, but it doesn’t stop early enough. For one frame, it partially overlaps the lower object, before “bouncing” back to the position it should occupy in the next frame. about 20% of the objects overlap.

In trying to solve that issue so that the object stops when its supposed to, I’ve given it the following code:

using UnityEngine;
using System.Collections;

public class down : MonoBehaviour {
	
	private float length = (1f);
	
	void Start () {
	rigidbody.velocity = Vector3.down;
	}
	
	void fixedUpdate () {
	RaycastHit hit;
	Ray landingRay = new Ray(transform.position, Vector3.down);
		//cast a ray from the object's origin downward with a length of one unit
		
			if (Physics.Raycast(landingRay, out hit, length))
			{
				if (hit.distance < 0.5f)
				transform.position = transform.position + (Vector3.up*(0.5f - hit.distance));
			}
			}
	//When the ray hits an object, check and see if the length between the ray's origin and
	//the hit object is less than 0.5, or one half of the falling object's diameter. 
	//If it is, move the object upward by the difference.
}

The idea being, if the distance from the falling object’s origin is less than half of its diameter, then it must be overlapping the other object, so it needs to move up until that’s no longer true.

This logic seems sound to me but this code does not appear to have any meaningful effect on the movement of my object. So:

-For my own understanding, what’s the flaw in my reasoning?

-More practically, how can I make the object stop when it hits another collider, instead of going into the collider, then popping into place on the next frame?

First off, your raycasting is not working because “fixedUpdate()” should be “FixedUpdate()” with an upper case ‘F’.

Other than raycasting, the other methods mentioned on this list to address this problem are:

  1. Setting Min Penalty for Penetration to 0.0: Edit>Project Settings>Physics

  2. Reducing the Time.fixedTimeStep: Edit>Project Settings>Time. Try reducing it from 0.02 to 0.01.

Hi,
In case anyone finds this thread and is still looking for a solution, reducing the Default Contact Offset does the trick.
You can’t set this value to 0 as with the Min Penalty for Penetration, but setting it to something like 0.001 should work.