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!