How could I make it so that I have a raycast that , when you hover over a gameobject with the tag “Small Crate” and then you press “e” you set this var I have, crateOpen, to true? Sorry I am not very good with Raycasting. I also need it to be so that you can only open it when you are about 2 units away. C Sharp please. And thank you for spending your time to help me out!
Here is:
void Update () {
if (Input.GetKeyUp(KeyCode.E)) {
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) {
if (hit.collider.CompareTag("Small Crate") && Vector3.Distance(hit.collider.transform.position, transform.position) <= 2.0f) {
crateOpen = true;
}
}
}
}
If you mean hover the mouse cursor wold be like this:
function Update () {
if (Input.GetKeyDown("e")) {
var hit : RaycastHit;
// Construct a ray from the current mouse coordinates
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)) {
if(hit.collider.tag == "Small Crate" && hit.distance > 2)
crateOpen = true;
}
}
}
I put first press key for performance.
I’m assuming your script is attached to the camera so you have to send the “crateOpen” variable.