ExplodingTiger
ExplodingTiger

Reputation: 367

Stop rigidbodies from moving after colliding

I have a very simple case: 2 cubes on a plane, the player can move a cube via mouse input.

Each cube has a collider and rigidbody attached, as well as a high friction material with 0 bounce.

What I want to achieve is: if one cube is to come into contact with the other, I want to stop both cubes from pushing each other or going into one another - I want them to act as walls to each other.

What I'm getting is this:

enter image description here

What I have tried is to switch on the IsKinematic option of the cubes while I drag them, but this lead to no result.

Here is my code:

private Vector3 screenPoint;
private Vector3 offset;
private Vector3 oldPosition;

private Rigidbody rBody;

private bool dragging = false;

void Awake()
{
    rBody = gameObject.GetComponent<Rigidbody>();
}

void OnMouseUp()
{
    dragging = false;
    rBody.isKinematic = false;
}

void FixedUpdate()
{
    if(dragging)
    {
        Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;

        cursorPosition.y = oldPosition.y;

        rBody.MovePosition(cursorPosition);
    }
}

void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(rBody.position);
    offset = rBody.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    oldPosition = rBody.position;
}

void OnMouseDrag()
{
    dragging = true;
    rBody.isKinematic = true;
}

Any help is appreciated. Thanks.

Upvotes: 0

Views: 2677

Answers (2)

Rad Buster
Rad Buster

Reputation: 1

Might not be the best solution but maybe try destroying the rigid body component after the collision enter, this way the cube will become a static object, thus turning into a wall. You can add the rigidbody again shortly afterwards.

Upvotes: 0

Stud
Stud

Reputation: 521

Did you try to put a physic material and tweek the settings (especially the friction settings)? If you did, and didn't achieve what you want, you could use MonoBehaviour.OnCollisionExit to detect when your objects aren't in contact anymore and either set the velocity to 0 or lock the position. If you lock the position, you'll probably need a coroutine to unlock it a while later. This solution may lead to strange bugs later (in case of bumpy move for exemple, where your objects lose contact for one frame only). I would prefer using the physic material if possible.

Upvotes: 3

Related Questions