0
\$\begingroup\$

So, I am making a Minecraft ripoff.
I have a raycast that hits a block. It then places a block inside of that block. I am trying to make it place next to the block in the direction the user is facing.
I got some of that figured out. I use:
Math.Round();
to round up the floats. My problem is figuring out what axis to round on. I need it to depend on the direction the player is facing to figure it out.
I tried doing a complicated algorithm to figure out which face of the collider the player is facing, but that didn't work out that well....
enter image description here

How do I solve this? I can't figure it out.

\$\endgroup\$
  • \$\begingroup\$ I am using Unity 2018.3.3f1 \$\endgroup\$ – Chey Moore Feb 18 at 0:46
  • \$\begingroup\$ you might find the answer to this question help, as I think theres some similarities even though the question is trying to solve something else: gamedev.stackexchange.com/questions/168001/…. \$\endgroup\$ – i.do.stuff Feb 18 at 18:23
1
\$\begingroup\$

You can base it off of the normal of the surface the Raycast hits. When performing a Raycast, there is an optional out parameter that supplies information about the resulting collision, including the aforementioned normal.

Here's a brief example of how you could do this:

RaycastHit hit;
if(Physics.Raycast(new Ray(transform.position, transform.forward), out hit) {
    objectToInstantiate.transform.position = 
    hit.collider.gameObject.transform.position + hit.normal * blockSize;
}

The object will be translated from the source block by the normal of the face that is hit by the Raycast. In case you're unfamiliar, the normal is the vector perpendicular to a given face (basically, what direction it's facing)

\$\endgroup\$
  • \$\begingroup\$ Thank you for your amazing help. It worked perfectly! \$\endgroup\$ – Chey Moore Feb 18 at 22:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.