Monday, May 7, 2018

2d - How can I implement a directional melee attack?


I am attempting to make a top down game similar to the SNES Zelda games, in Unity 4.3, in 2D. When my character swings their sword, every enemy within a radius takes damage. I want to make sure that melee attacks only damage enemies the player is facing.


How can I do this?





The relevant code in PlayerAttack.cs looks like this:


// Update is called once per frame
void Update () {
// have the player initiate an attack on the object
if(Input.GetKeyUp(KeyCode.F)){
MeleeAttack();
}
}


private void MeleeAttack(){
// create a variable called distance to make sure the distance is close enough
// to inflict damage from a melee attack target.transform.positon = the position
// of the object to attack and transform.position is the position of the players
// transform
float distance = Vector3.Distance(target.transform.position, transform.position);

// make sure the distance is not greater than 1.5 so the player cannot
// melee an enemy from to far away
if(distance < 1.5f){

// get a reference to the enemy's health script and type cast it.
EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
// now call the function that will decrease the enemy's health
eh.AdjustCurrentHealth(-10);
}
}


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...