3
\$\begingroup\$

I made a melee combat system for my game. The code looks like this:

var hit:RaycastHit;
    if(Physics.Raycast(transform.position,transform.forward,hit)) {
        if(hit.distance<=2.0) {
            Debug.LogError("Hit!");
            Debug.LogError(hit.collider.tag);
            if(hit.collider.tag=="Enemy") {
                Instantiate(bloodFX,hit.transform.position,transform.rotation);
                hit.transform.SendMessage("ApplyDamage",25,SendMessageOptions.DontRequireReceiver);
            }
        }
    }

However, when an object with the tag "Enemy" stands in front of a "Tree" object, the log tells me that it's hitting the tree tag and not the enemy. What am I doing wrong here? The collision boxes are all correct.

Thanks!

P.S. This is for the ludum dare that ends in 4 1/2 hours so I have to fix this quickly.

\$\endgroup\$
  • 3
    \$\begingroup\$ Any chance the enemy object is set to the "Ignore Raycast" layer? Unfortunately this isn't really something we can diagnose just by looking at a few lines of code; for starters, I'd need to see what exactly "the collision boxes are all correct" means. \$\endgroup\$ – jhocking Dec 7 '14 at 22:51
3
\$\begingroup\$

Hope this may help : (from Physics.Raycast docu)

Notes: Raycasts will not detect colliders for which the raycast origin is inside the collider. If you move colliders from scripting or by animation, there needs to be at least one FixedUpdate executed so that the physics library can update it's data structures, before a Raycast will hit the collider at it's new position.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Your note saved my life, thanks \$\endgroup\$ – Ashen One Jul 26 at 0:26
1
\$\begingroup\$

I suggest for a quick fix just implement your weapon using collision boxes with trigger assignments then go from there

void OnCollisionEnter(Collision col){
    if(col.collider.gameObject.name == "Enemy" /*or tag*/){
      //apply damage!
    }
}

P.S Thanks for helping me fix send message haha I hope this helps you!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Instead of Physics.Raycast, use Physics.RaycastAll.

I'm pretty sure I've run into this same problem and I don't see it in the documentation for Raycast but it's in RaycastAll that order is not guaranteed. I assume this carries over to Raycast as well. Even if it doesn't and this doesn't solve the issue for you it should be able to assist because it will give you a full list of everything that IS triggering a hit.

RaycastAll returns a RaycastHit[] you can simply iterate over, checking their distances.

Documentation: http://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.