raycast hit wrong point . this script give to sniper weapon.
raycast does not hit object(add animation)
please help
#pragma strict
function Start () {
}
function Update () {
var cam : Transform = Camera.main.transform;
var ray = new Ray(cam.position, cam.forward);
var hit : RaycastHit;
if(Physics.Raycast (ray, hit, 500)) {
if (Input.GetMouseButtonDown(0) && hit.collider.gameObject.tag == "Enemy") {
print ("enemy!");
Destroy(hit.collider.gameObject);
}
}
}
I see nothing wrong with your code that would account for the described behavior. About 50% of the time this issue comes across the list either 1) the name/tag of the game object is not what is expected, or 2) the ray is hitting an unexpected game object. In addition, it is a bit more efficient to place the GetMouseButtonDown() outside of the Raycast(). That way, you don’t do a Raycast() each frame. Try this code. I’ve added a Debug.Log() for the name and the tag.
#pragma strict
function Update () {
var cam : Transform = Camera.main.transform;
var ray = new Ray(cam.position, cam.forward);
var hit : RaycastHit;
if (Input.GetMouseButtonDown(0)) {
if(Physics.Raycast (ray, hit, 500)) {
Debug.Log(hit.collider.name + ", " + hit.collider.tag);
if (hit.collider.tag == "Enemy") {
print ("enemy!");
Destroy(hit.collider.gameObject);
}
}
}
}
Try getting a list of all colliders on front of the camera. Then exclude some unwanted colliders, if any (like your gun collider, for example).
Use different tags for player and head.
The code (in C#, sorry for non-conversion to JS) may look like this:
Raycast.cs:
using UnityEngine;
using System.Collections;
public class Raycast : MonoBehaviour {
void Start () {
}
void Update () {
if( Input.GetButtonDown( "Fire1" )) {
Vector3 start = Camera.main.transform.position;
Vector3 direction = Camera.main.transform.forward;
RaycastHit[] hits = Physics.RaycastAll (start, direction, float.PositiveInfinity);
Debug.DrawRay ( start, direction * 10 , Color.red, 10);
foreach(RaycastHit hit in hits){
Debug.Log("hit.collider="+hit.collider+" hit.point="+hit.point+" tag="+hit.collider.tag);
if(hit.collider.tag == "Player" || hit.collider.tag == "PlayerHead") {
Debug.Log ("Shoot "+hit.collider.tag);
}
}
}
}
}
I did a small test project with this issue, you can try it from here . Look for “HeadCollider” object attached to the head of default Unity 3rd Person Controller.
thankyou. result of trying your code and debug.
There are problems with object(add animation)probably.
I changed different object. It worked
i resolve problem. thanks