- Home /
How to Stop a Game Object from Passing through a Collider while it's being Dragged?
I have game objects with rigid bodies and box colliders attached to them. I also have a script attached to them that allows me to click and drag them around when the mouse button is down.
However, when I click and drag them around and pass through the ground, which also has a rigid body and box collider on it, the game object that I am dragging around passes through the collider.
That's the problem.
How can you stop the game object that is being dragged around from passing through the ground while it's being dragged?
The game object should just stop being dragged when it hits the ground, not pass through it.
Any help is appreciated.
Thanks in advance.
Answer by mattssonon · Nov 11, 2013 at 11:02 PM
Use Rigidbody.MovePosition()
to move the Game Objects. If you use, say, Translate()
colliders won't behave like you want them to.
Right idea, but I think even $$anonymous$$ovePosition will gladly put the object through a wall. If you keep the movements very small (like current position + tiny bit) physics will correctly "pop out" translate and $$anonymous$$ovePosition.
To be sure, think you need to go one step further and use AddForce (or set velocity directly.) But that can give the object an odd spring-like wiggle.
I've tried both suggestions, it still passes through.
Any ideas for using OnCollisionEnter() or similar?
Well, you can use OnCollisionEnter()
to check if it registers a collision at least. Try moving the objects further than normal with each drag to see if @owen-reynolds is right.
Answer by _Yash_ · Oct 04, 2015 at 08:50 AM
Here is the easy and great solution, its late but worth sharing so...it also answers Why and How... https://youtu.be/ZfjVR-0ZFHU hope it will be helpful.
Thank you Yash :) , the video in your link solves this problem.
Answer by Owen-Reynolds · Nov 13, 2013 at 03:13 PM
If using only Addforce is putting your object through the ground, then something else is wrong. Maybe another part of the script, or some other script is messing up, or the set-up is wrong (triggers? bad layers -- but that can't happen by mistake.) Unless the speeds are crazy high (depends on the command.)
Maybe copy the scene, try just dropping the object on the ground (start it so it falls) and comment out parts of the the script so it just gives a single push/move/whatever.)
Also, the ground doesn't need a rigidbody -- just a collider. A rigidbody won't hurt (but then the ground will fall,) and can check isKinematic (but then easier just not to have it.)