- Home /
How to get raycast and key click info.
I know the title blows, I didn't know exactly how to explain it. But what I have is a raycast connected to my flashlight which is basically a pointer in the game. I want it so when I go to specific objects and press "e" while a raycast is hitting something actions can take place.
Example:
Walk up to a barn door, it's within "1" distance
Press "E"
Barn door recognizes the key press and raycast
Barn door goes about it's business.
Here's my current code, if someone could help me out I'd be extremely grateful. This code is attached to my point light (Flashlight)
function Update () {
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, 1)) {
if (Input.GetKeyDown(KeyCode.E))
{
print("I pressed E while aiming at an object!");
}
}
}
Answer by Sundar · Aug 24, 2012 at 09:44 PM
In your case it is most likely the distance 1 unit is too small( I'm just assuming ), you can debug it - as
function Update () {
float dist = Vector3.Distance( barnDoor.transform.position, transform.position );
Debug.Log( dist );// assuming barnDoor being a gameobject
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, 1)) {
Debug.Log("Close enough to press key e" );
if (Input.GetKeyDown(KeyCode.E))
{
print("I pressed E while aiming at an object!");
}
}
}
If it is true, modify the value appropriately using dist values in the console
Your answer
Follow this Question
Related Questions
Key press hides object and spawns another 2 Answers
Rotating an Object on Key Press! 3 Answers
Rotate on Key press help? 1 Answer
How do i make the object at the end of my raycast not phase into a wall? 2 Answers
Is Object At Location? 3 Answers