- Home /
Placing a cube at the point you look at, without overlapping.
I want to place a cube a certain distance form the player and at a point defined by a raycast going from the camera.
I do a raycast that is rotated so it is following the camera's rotation and I create a simple cube at the hit point. Now the cube is created but since its origin is in the center it is half sunk into the object it was created on.
I need it to be placed on the object I'm facing and not sunk into it. I am not sure how I'd do this since the hit normal doesn't really fix the problem. Any ideas?
Please ask if you don't understand the question.
Answer by robertbu · Mar 08, 2014 at 10:32 PM
It sounds like you are most of the way there. Typically you use the hit.normal to move the point up. Something like:
var pos = hit.point + hit.normal * halfObjectHeight;
...where 'halfObjectHeight' is the distance from the bottom of the object you are placing to its pivot point. The value for a default cube will be 0.5 if not scaled. If it is scaled it will be 0.5 * transform.localScale.y;
I did try something like that and it works fine but that does still not prevent the cube from overlapping other objects if you try to place it in a corner.
The general solution (arbitrary mesh within and among other arbitrary meshes that moves itself to fit if it can) would be a very complex problem. So the question becomes what (if any) simplifications you are willing to live with. And that is completely based on the nature of your game and the game environment.
One common solution is to not allow the user to place a cube if it hits anything (except the floor). There is no perfect solution for figuring out if the object hits another. Often Physics.SphereCheck() or Physics.OverlapSphere() is used. This will produce false positive hits, but it is very easy to do and can assure that nothing collides.
Another approach might be to use an invisible object with a Rigidbodey, wait a frame after placement to collect the collision information to deter$$anonymous$$e if placement is valid.
If your geometry is simple, you can add some additional Raycasts to move the object away from floors and other object. But this solution has to have a fallback since there are unsolvable problem (like trying to place an object between two other objects where there is just not enough room).
I'm a bit late out with accepting heh, I was just thinking about if I could make a invisible collider to the object and try to detect collisions when I try to place a object but I haven't got around to actually testing that solution. As you said it seems quite difficult to place an object without collisions, but I'll try some of your suggested solutions. Thanks for your answer though!
Your answer
![](https://koobas.hobune.stream/wayback/20220613135727im_/https://answers.unity.com/themes/thub/images/avi.jpg)