How do i make a sword only do damage to an enemy when the left mouse button is clicked?
I have a script that whenever the enemy is collided with the sword, it takes 10 damage from the enemy. The problem is that the enemy takes damage just by the character walking into the enemy. I want it so that the enemy can only take damage from the sword when the left mouse button is clicked. How should I do this? This is my code so far:
var enemyHealth : int;
function Start () {
enemyHealth = 100;
}
function OnTriggerEnter(coll : Collider) {
if(coll.gameObject.tag == "Sword"){
enemyHealth = enemyHealth-10;
Debug.Log("Enemy Hit with Sword and health is" + enemyHealth);
}
}
function Update () {
if(enemyHealth <= 0)
{
Destroy(GameObject.FindWithTag("enemy"));
Debug.Log("Enemy Died");
}
}
Answer by Zodiarc · Nov 03, 2016 at 02:18 PM
function OnTriggerEnter(coll : Collider) {
if(coll.gameObject.tag == "Sword" && Input.GetKeyDown(KeyCode.Mouse0)){
enemyHealth = enemyHealth-10;
Debug.Log("Enemy Hit with Sword and health is" + enemyHealth);
}
Usually, when i don't add && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.$$anonymous$$ouse0) whenever the sword collided with the enemy, it took damage from the enemy, when I added that to the script however, no matter if I clicked the Left $$anonymous$$ouse Button, it still wouldn't take damage from the enemy. It's strange cause you would think that it could work but it just doesn't seem to work.
Update: The script does make the enemy take damage but the problem is that you need to rapidly click the left mouse button for the enemy to take damage. I want it so that the animation on the sword could play, and during that period of time, the enemy would take damage. What do I add to the script so that the enemy could take damage from a single mouse click, but lengthen that time to say 3 seconds?
Play the animation first with the Input.Get$$anonymous$$ouseButtonDown condition or whatever it fits and then detect if it hits any enemy colliders. If i am not mistaken you run that script on the enemy and not on the player. You got to do it the other way around.To avoid hitting anything while you are not attacking try to deactevate the trigger or the collider on the sword or try a condition that checks if the animation is playing i am not sure if there is a direct way to do it like bool : animation.isPlaying or something like this.
Your answer
Follow this Question
Related Questions
unity 5 car traffic system 0 Answers
How to reference script in unity (C#) ? 0 Answers
Unity 2d Collision Glitch Help 0 Answers
Rotation animation keyframes problem 1 Answer
How to decreased the visible particles 0 Answers