- Home /
How to use Raycast to open a crate?
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!
Answer by SkaredCreations · Mar 22, 2014 at 06:24 PM
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;
}
}
}
}
Would a script like this need to be attached to the player?
Yes because it uses transform.position in the calculation of distance, if you want to attach to something else then you need to change it to use the player transform position there.
Answer by Ozzyel-PT · Mar 22, 2014 at 06:41 PM
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.