int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(x, y));
RaycastHit hit = new RaycastHit();
Physics.Raycast(ray, out hit);
if (hit.collider.tag == "Player")
{
SomeFunction();
}
The problem is that the if statement is never true, I have a crosshair (GUITexture) drawed in the middle of the screen, when I focus it on a player and I shoot it’s like that I don’t shoot to the player.
public int range;
void Update () {
Vector3 direction = object.transform.TransformDirection (Vector3.forward);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast (transform.postion, direction, hit, range ) (hit.collider.gameObject.CompareTag("Player"))){
Somefunction();
}
}
this would cast a ray along the Z axis from the position of the transform so be sure the local coordinates are set to 0. it recognizes the player tag if that’s what you want?
This is what you are looking for however it is in javascript but the code is virtually identical in C# so there should be no problem converting it.
var direction = transform.TransformDirection(Vector3.forward);
var ray = Camera.main.ScreenPointToRay(Vector3(Screen.width/2, Screen.height/2,0));
var hit : RaycastHit;
if(Physics.Raycast(ray, hit, range))
{
Debug.DrawLine(ray.origin, hit.point);
if(hit.transform.tag == "Player")
{
hit.transform.SendMessage("function name", SendMessageOptions.DontRequireReciever);
}
}