- Home /
Help finding out which side of a cube a raycast hits
I'm making a voxel based game, and I'm trying to make placing blocks act similar to minecraft in the sense that the voxel is created adjacent to the side of a preexisting voxel that the player clicks. I successfully did this part by comparing the origin of the 1 meter cube and checking which direction it was 0.5 meters away from. The catch is that I need to get this to work if the cube is at any rotation. If I use RaycastHit.point, those number are less valuable without taking the rotation into account and I'm really unsure of how to go about doing that. I'm using c#
Any advice would be great.
Answer by crohr · May 28, 2015 at 05:33 AM
I believe this is what you are looking for. Or something like that.
var newBlockPostion = hit.transform.position + hit.normal;
var newBlockRotation = hit.transform.rotation;
Thanks for the reply, but would you $$anonymous$$d explaining a little bit more how hit.normal would work? I understand that it's a Vector3 that points away from the collider, but how far and such?
Yes, so hit.normal is a unit vector, so it has a length of 1 unit. Thus, (hit.transform.position + hit.normal) will give you a vector position that is 1 unit distance away from the center of hit object in the direction of hit.normal. I did not test this for your specific needs, but I believe this should work.
It worked out great! Thanks a lot. Just curious though, is there any way to change the unit to 2 or more units away?
Yes there is. hit.normal * (whatever x number of units you want). Since, a vector multiplied by a scalar simply modifies the length of the vector, you are given a vector that is x units in length.