Question by
SirDogey · Feb 21, 2017 at 12:24 PM ·
unity 5script.2d spritespickup
How do i make a object run a function when i click "f" on it While the middle of the screen is hovering over the object.
So i want to kinda Have a item pickup system but i can do the pickup part. So i just want to be able to have my object run a function when the player has the middle of his screen hovering over the object and clicks "f" TAnd have a 2d image show up on the screen while hovering over it. That Is All thanks!
Comment
Best Answer
Answer by Deathdefy · Feb 22, 2017 at 09:08 PM
public class Test : MonoBehaviour {
//how far you want the ray to fire
private float distance = 100.0f;
void Update ()
{
//where your ray is coming from
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
//what you are hitting with your ray
RaycastHit hit;
//draws a line in your scene to show you were the ray is.
Debug.DrawRay(ray.origin, distance * ray.direction, Color.red);
//this will only hit something that has a collider on it, and will only hold the first object hit
if (Physics.Raycast(ray,out hit,distance))
{
//we hit this object
Debug.Log(hit.collider.gameObject.name);
if(Input.GetKeyDown(KeyCode.F))
{
Debug.Log("We are hitting something and pressed the F key");
}
}
}
}
One thing i an not the best at scripting so how do i set where it comes from i have a First Person Controller as my camera. Thanks for Answering Though! @Deathdefy