Bob
Bob

Reputation: 91

Unity3D Raycasting

Writing a C# script that allow player to construct with simple blocks. For this reason, I strike a raycast forward from playercam. When ray hit some object - I get the collison world coords with hit.point If I Instantiate a constructing block on that coordinates - it will be created overlapping with other objects. I have to change coords.

enter image description here

How can I get the point that lay as shown in the picture above? This will allow me to calculate created blocks' coordinates

Upvotes: 2

Views: 932

Answers (1)

Problematic
Problematic

Reputation: 17678

You can take the RaycastHit's point property and move out along the intersected face's normal to your block's extent (half its width; if it's a unit cube, this will be 0.5f); something like this:

if (Input.GetMouseButtonDown (0)) {
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast (ray, out hit)) {
        Instantiate (prefab, hit.point + hit.normal * blockExtent, hit.transform.rotation);
    }
}

This will instantiate your new block at the raycast's intersection point (you'd need to calculate the center of the intersected face if you wanted them to align precisely), and inherit the rotation of the intersected GameObject.

Note that this won't prevent a new block from spawning inside an existing block; it will just keep it from spawning inside the block that you raycasted against.

Upvotes: 3

Related Questions