- Home /
OnTriggerEnter - Melee Combat
Can someone explain how this is done please? I'm trying to do melee combat for my game and I have animated my sword to swing. I've never used this before and have no idea how to implement it and the api isn't very helpful.
I have added an empty object and a box collider around the blade of the sword. I've added it as a child of the sword and have ticked Is Trigger. This is the script I have so far.
function OnTriggerEnter ( other : Collider )
{
if ( other.tag == "Enemy" ) // or what ever you want to identify the object
{
other.GetComponent("EnemyHealth1").AdjustCurrentHealth(-10);
Debug.Log("Enemy Hit!!");
}
}
But it doesn't seem to be doing anything.
This is the script for the health and AdjustCurrentHealth
var hp:float; // health value, 0..maxHp
var maxHp:float;
var healthBarWidth:int = 20;
var myHealthBar:GameObject;
private var myHb:GameObject;
var posX:float;
var posY:float;
var show: float = 0; // health bar appears when show > 0
var duration: float = 0.6; // health bar vanishes for duration seconds
function Start () {
myHb = Instantiate(myHealthBar, transform.position, transform.rotation);
}
function AdjustCurrentHealth(adj : int) {
hp += adj;
}
function Update () {
if (show>0){
myHb.guiTexture.color.a = show; // variable show controls the bar alpha
show -= Time.deltaTime/duration; // fades out health bar unless show is recharged
myHb.transform.position = Camera.main.WorldToViewportPoint(transform.position);
myHb.transform.position.x -= posX;
myHb.transform.position.y -= posY;
// myHb.transform.localScale = Vector3.zero; // <- this does nothing
var healthPercent:float = Mathf.Clamp(hp / maxHp, 0, 1);
myHb.guiTexture.pixelInset = Rect (0.02, -0.09, healthBarWidth * healthPercent, 5);
}
}
The health script is attached to my enemy and the melee attached the the empty game object with the box collider.
Try starting with a smaller test: comment out AdjustCurrentHealth and try to get only the Debug to run. Things to check: has the enemy tag been set to "Enemy"? Try selecting the arm in sceneView to be sure it's moving with you. In general, the "moving triggerBox" idea does work.
Answer by Peter 8 · Jun 28, 2012 at 04:48 PM
OnTrigger functions require a rigid body attached as stated here: http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnTriggerEnter.html. usually put it on the moving element. just set the rigid body to is kinematic so it isnt affected by any forces acted upon it.
Your answer
Follow this Question
Related Questions
How can i detect collision in melee combat? 2 Answers
Multiple Melee Weapons 2 Answers
Melee Combat 1 Answer
melee combat 0 Answers
Trigger and ennemy damage 2 Answers