How can I get a rigidbody to follow my cursor without penetrating through colliders?

I’m trying to get a rigidbody to follow a target point (controlled by the mouse) that is moving around inside an enclosed mesh collider for my level. If the target point leaves the mesh collider, I need to guarantee that the rigidbody stays inside. I.e. if it can’t reach the target point, it calmly presses against the mesh collider until it can.

I tried using rigidbody.MovePosition, but the rigidbody “bleeds through” walls it pushes up against, then starts vibrating violently and finally penetrates right through when the target point moves outside the mesh collider.

I tried implementing my own version of “MovePosition” by calculating the rigidbody’s velocity to match the target point’s position, but there was near-identical behavior as MovePosition.

Is there some way I haven’t thought of to achieve what I’m after? Thanks!

I stuck with adjusting the velocity according to mouse displacement and switched Collision Detection to Continuous, which solved my issues with penetration. A simplified version of my movement code:

rigidbody.velocity = ( ( transform.right * mouseMovement.x ) + ( transform.forward * mouseMovement.y ) ) / Time.deltaTime;

The rigidbodies still have an ugly jitter when they collide with walls, especially in corners. I’ve smoothed this out by averaging the last couple frames of motion, so while it feels slightly mushy, at least it’s smooth and not going through walls.

How about upping the drag some and then using AddForce() to move the object in the direction of the cursor. I just ran a quick test with a sphere inside four wall with the following code, and it worked fine:

#pragma strict

function Update () {
	var pos = Input.mousePosition;
	pos.z = -Camera.main.transform.position.z;
	pos = Camera.main.ScreenToWorldPoint(pos);
	var dir = pos - transform.position;
	rigidbody.AddForce(dir * 10);
}

After a few hours of pain I went to this simple code

 Vector3 destintaion; //you fetch it in advance
 float sens = 10; //sensetivity
 
 GetComponent<Rigidbody>().velocity = (destination - transform.position) * sens;

Collider2D col1,col2;
col1 = GameObject.Find(“objectname”).gameObject.GetComponent();
col2 = GameObject.Find(“objectname”).gameObject.GetComponent();
Physics2D.IgnoreCollision(col1, col2, true);

This works great!
@calbar