Place item at Raycast hit?

The title pretty much explains my problem. Currently, the object is being placed on the ground, but not at the right position. When I click and the player places an object down on the ground, the item is stuck on the ground. I know that this is because that the X, Y, and Z’s of the hit is exactly where the point is.

But how do I make it where if the object is going to be placed on the ground, then raise? Or, if the object is going to be placed on a wall, subtract OR add to the X or Z position to make up for the difference?

Here is the line the sets the position:

currentHeldObject.transform.position = new Vector3(hit.point.x, hit.point.y + renderer.bounds.extents.y, hit.point.z); //Sets held object's pre-place position

You’ll notice that I already try to raise the object in the Y position. This works for the ground, but when the object gets placed on a wall, it is raised too much. How can I fix this? It is confusing me lol.

I would personally cheat and manually assign each object a root position to use for instantiating.

I would probably cheat too. If you don’t want to cheat, maybe you could check the normal of the raycasthit, use the dot-product against world-up and multiply by that. Something like:

float upDot = Vector3.Dot(hit.normal, Vector3.up);
currentHeldObject.transform.position = new Vector3(hit.point.x, hit.point.y + renderer.bounds.extents.y * upDot, hit.point.z);
1 Like

Dang… I had this idea at the back of my mind, but the reason I didn’t want to do this is because I plan on having a lot of objects that you can pick up through out the game.

I can just attach a script to the “Obtainable” objects, and inside that script, include a root position. But then I run into another problem. I won’t know if the object’s position needs to be increased in the X, Y, or Z position.

I wish this was easier, but it appears not to be,

This gave me the same exact effect I had earlier lol. Thanks though.

Treat the root position as an offset and just add it to the raycast hit position.

Yes, it should give the same effect when doing it towards the ground/roofs, but it shouldn’t recieve any upwards offset when shooting against walls. You can apply the same thing for your x/z displacement, but it’s hard to get a grasp on the result you want. Cheating is probably easiest.

1 Like

Omg thank you! This was so simple. Cheating actually isn’t easiest. I just needed three Vector3.Dot variables, and it works! It is a little rough, but it doesn’t need to be perfect. Thank you man, I really appreciate the help.