Collider2D information outdated?,

I am quite new to Unity and I just started working on a 2D platformer, more precisely on the movement of the playable character. Now, when it comes to collision detection, the information returned to me by the Collider2D seems to be outdated, as I can enter one frame’s worth of movement into any wall and will only get pushed back to where I am supposed to be once I let go of the button. So if my character is walking right and should be at x = 15 to just touch the wall, he will be stuck at x = 15.1 until I let go of the right arrow key. Maybe I just messed up the order of code or maybe something else, whatever it is, if anyone could help me, I would be most grateful. The code is given below.

void FixedUpdate()
    move = Input.GetAxisRaw("Horizontal");
	velocity.x = Mathf.MoveTowards(velocity.x, speed * move, Mathf.Abs(move) * acceleration + (1 - Mathf.Abs(move)) * deceleration);
	Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);
	foreach(Collider2D hit in hits)//push the character out of potential intersections after movement
			ColliderDistance2D colliderDistance = hit.Distance(boxCollider);

			if (colliderDistance.isOverlapped && colliderDistance.isValid)
				transform.Translate(colliderDistance.normal * Mathf.Abs(colliderDistance.distance));

You don’t move with the physics system at all. You manually force move the object using the transform component and then let the physics system detect the overlap. This is not how the physics system should be used. You essentially try to manually implement your own physics system on top of Unity’s Box2d physics by just picking out certain information from the physics system.

Note that Box2d (Unity’s “Physics2D” engine) as well Nvidia’s PhysX (Unity’s 3d “Physics” engine) have their own representations of all objects relevant for physical interactions. Unity does not automatically update those whenever you change the corresponding object in the Unity engine. This is done automatically when Unity performs a physics step. However since you essentially roll your own system the syncronisation of all colliders happens the next frame. You could use Physics2D.SyncTransforms after you changed the position / rotation of a collider and before you try to check any overlaps using the Physics2d system.

Over all I don’t really get the point of rolling your own rudimentary collision response implementation. You don’t modify the velocity when a collision happens. Is there a reason you don’t want to use Unity’s rigidbody simulation?

ps: Note that in general, moving a collider without a rigidbody can cause huge performance issues because all colliders without a rigidbody are considered stationary. They might be baked into one static collision model. So moving individual colliders would essentially rip that model apart each time a collider is moved.