- Home /
Rotate Raycast in 3D Space
Hey, so I've been trying recreate Minecraft in Unity to sharpen my skills, so I've been using Raycasts to detect the 'block' that is front of you. Currently, I am using the Standard Assets FPS Controller with a Ray coming out of the camera. I have been looking everywhere and I cannot find any answers so I apologize if this has already been answered.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockManager : MonoBehaviour
{
public GameObject selectedBlock;
public Transform player;
private RaycastHit hit;
private Vector3 RaycastStart;
void Start() {
RaycastStart = new Vector3(player.position.x, player.position.y, player.position.z);
}
void FixedUpdate()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
// Vector3 rotFwd = new Vector3(fwd.x /*player.transform.rotation.eulerAngles.x*/, /*fwd.y*/ player.transform.rotation.eulerAngles.y, /*fwd.z*/ player.transform.rotation.eulerAngles.z);
RaycastStart = new Vector3(player.position.x, player.position.y, player.position.z);
if (Physics.Raycast(RaycastStart, fwd, out hit, 10) && hit.transform.tag == "DestructableBlock") {
Debug.Log("There is a block in front of the object.");
Debug.DrawRay(RaycastStart, fwd * hit.distance, Color.yellow);
} else {
Debug.DrawRay(RaycastStart, fwd * 10, Color.yellow);
}
}
}
As you can see, selectedBlock is not being set yet, as I am still focusing on the rotation. I need the raycast to point forward in front of the camera (whatever the rotation is) (like in minecraft) to detect any 'block' in front of the camera. I have not been able to find an answer but I feel like its obvious. Thanks!
Answer by qobion · Mar 24, 2019 at 11:21 AM
You shooting rays in forward direction of your blockmanager gameobject. If this script is not attached to your players transform you should use : Vector3 fwd = player.TransformDirection(Vector3.forward);
This solves my issue about rotation! Thanks! But, one more thing, is it possible to make the raycast rotate up and down as well?
Sure. Just shoot your ray directly from the camera:
Transform camera;
Start ()
{
camera = Camera.main.transform;
}
FixedUpdate()
{
Vector3 fwd = camera.TransformDirection(Vector3.forward);
}
This results in NullReferenceException: Object reference not set to an instance of an object Block$$anonymous$$anager.FixedUpdate () (at Assets/Assets/Scripts/Block$$anonymous$$anager.cs:21)