- Home /
Detecting Raycast collision on an enemy to deal damage
Background:
Creating a 3rd person shooter and I have the hero shooting his pistol which creates a ray since the bullets move too fast for projectiles, ect.
I want the robot to be able to take damage when hit. This is what I have but it doesnt seem to be working. Im REALLY new to scripting so I'm kind of lost but I need to do this for a project. The main problem I'm having is that the robot is written in javascript but the player is in c# since they were assets from the asset store..
as for the code:
For the gun shooting the ray (c#):
void OnFire () {
Vector3 dir = aimTarget.position-aimPivot.position;
dir.Normalize();
Ray ray = new Ray(aimPivot.position, dir);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000, mask)) {
hit.transform.root.SendMessage("OnHit", new RayAndHit(ray, hit), SendMessageOptions.DontRequireReceiver);
}
}
As for the robot..
function OnRayCollision(rayCollision : RayCollision)
{ if (rayCollision.ray.CompareTag("robot")) hitpoints=0; }
Answer by Berenger · May 11, 2012 at 03:34 AM
I don't know what OnRayCollision is, but it's not from Unity, unlike OnTrigger... or OnCollision...
A message is send to the target. If there is a script implementing the function OnHit taking a RayAndHit in parameters attached to the same GameObject as the collider being hit, it will be called. Make sure sure there is such a function, that the spelling is right and that the parameter is correct.
I read up more on this subject since it seems like it's been asked many times, however I still cannot get it to work. I tried your suggestions and the gun shoots the ray, but I'm still having trouble with the robot detecting being hit by it. (I set the damage to instant kill the robot for testing purposes)
function Update () {
var hit : RaycastHit;
if (Physics.Raycast (hit)) {
hitPoints = 0;
}
}
In short, nothing happens and I actually get the following error:
Assets/WeaponScripts/CharacterDamage.js(18,25): BCE0023: No appropriate version of 'UnityEngine.Physics.Raycast' for the argument list '(UnityEngine.RaycastHit)' was found.
I really cant figure this out,it's not like I havent tried, because I've spent a few days trying to fix it.. can ANYONE help?
You need to provide more information about the ray to be cast! Simply saying 'raycast' isn't enough. It's like saying 'go', but not telling it what direction to go in!
if(Physics.Raycast(transform.position, transform.forward, hit))
{
// shot a ray out the front!
}
And no, it's not because you haven't tried- it's because you haven't read the scripting reference! It's very clearly laid out there how all this works. You should really have read it before even posting here in the first place!