Raycast Help.

I read that I can use raycast to get tell if it hits something. But I’m having trouble getting it to work. (Mainly the scripting.) I need it so at a certain distance away, if a character sees another the player you lose. Or a text is displayed. Can someone help me out with this?

Hey, I’m only starting but I am sure some one on the forums will help you out. Here’s my thought:

// script should be attached to the main camera

var hit:RaycastHit = new RaycastHit();

function Update () 
{
	var ray:Ray = Camera.main.ScreenPointToRay(Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
//300 is the distance for Raycast, and when mouse is down it will print the coordinates
	if(Physics.Raycast(ray.origin,ray.direction, hit, 300)  Input.GetMouseButtonDown(0))
	{
		//this will print the coordinates where the mouse is when its clicked
        print("clicked on" + hit.point);
		//here you need the code which I don't know to find the person or whatever you are looking for.
		
	}
//this will display a blue line which will follow the mouse
	Debug.DrawRay(ray.origin, ray.direction*300, Color.blue);
}

I can only help you so much at the time as I am still learning, Unity Help is really useful! You should try to use it. Good job Unity for making help so easy to navigate!

Thanks this helped me out. I attached it to the main camera. Though my game is a First Person game. So I’m not sure if it’s doing what it’s supposed to be doing.
Edit:
This is working! But how would I set it up to display it on the screen? Would it be like a guiText.text “”? Well thanks for the script, it works.

Hey, not sure what you want to display? Could you make your question a bit more clear? Maybe then I will be able to help you out. :slight_smile:

If the mouse click or sees a certain object. It would display the text on screen. Like in a guitext. Is that more clear?

*Untested

var didseeobject = false;

function OnGUI()
{
if (didseeobject)
{
GUI.Label(Rect(0,0,100,100),"Booyah, I saw you!")
}
}

If I put a check in the checkbox, it’ll always show the guitext. I need it when a certain object sees it.

You are supposed to set it up so that when the camera sees the character, it turns on the variable.

For instance…

*Untested

var hasclickedobject = false;
var ob : GameObject;//The object to be clicked on.
function Update ()
{
var hit : RaycastHit;
var ray = this.camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, hit, 10000))
{
if (hit.transform.gameObject == ob  Input.GetMouseButton(0))
{
hasclickedobject = true;
}
}
}

function OnGUI ()
{
if (hasclickedobject)
{
GUI.Label(Rect(0,0,300,100),"ARRRGH!! I've been clicked!")
}
}

Yes! Just what I needed! This works. Just need to set it up and I’m good. Thanks.

No problem.