Melee - Raycasting Distance, Sending Message

Hello,

I’m working on a simple melee system, basically I have an axe, that every time you click, an animation plays of your character swinging the axe. Also on the script, I have a raycast system, that detects the distance of the player and the enemy. If the distance is close enough, then allow the ‘melee click’ to do damage (SendMessage).

But it doesn’t seem to be working. I think I’ve narrowed it down to my SendMessage event, not sure if thats getting across for some reason, anyway, have a look and let me know what you think. (Right now, there is no ‘click’ as soon as the player gets close to the enemy, it will trigger the damage):

function Update () {
	
	enemy = GameObject.Find("/Player(Clone)Remote");
	
	var closest = enemy;
	var direction = enemy.transform.position - transform.position;
	
	var hit : RaycastHit;
	var layerMask = 1 << 10;
	
	if(Physics.Raycast (transform.position, direction, hit, Mathf.Infinity, layerMask)){
		Debug.DrawLine (transform.position, hit.point, Color.blue, 1);	
		
		if(hit.distance <= 2.0){
			//we are in melee distance
			print("** In melee distance! ** | Distance: " + hit.distance);
			//hit.collider.gameObject.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
			//enemy.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
			
			//if(GameObject.FindWithTag("Player")){
				hit.collider.transform.root.SendMessageUpwards("ApplyDamage", 110, SendMessageOptions.DontRequireReceiver);
			//}
		}
	}
}

I had several troubles once trying this raycast approach: the ray were too high or too low, started behind the point I supposed, hit the character collider, and many others.

You could show the name of the hit object, and use the option RequireReceiver to check if the function ApplyDamage was found in the target - check also if ApplyDamage actually exists in the target and it’s at a suitable hierarchy level (equal or above the collider owner):

    ...
    if(Physics.Raycast (transform.position, direction, hit, Mathf.Infinity, layerMask)){
       Debug.DrawLine (transform.position, hit.point, Color.blue, 1);    
       if(hit.distance <= 2.0){
         //we are in melee distance
         print("Melee at "+hit.distance+" of "+hit.collider.name);
         hit.collider.SendMessageUpwards("ApplyDamage", 110, SendMessageOptions.RequireReceiver);
       }
    }
    ...

Another approach for a melee is to add a trigger and a kinematic rigidbody to it (a moving trigger needs a rigidbody to work, and being kinematic it will not react to gravity, forces etc.), and use its OnTriggerEnter to handle the damage.