- Home /
Character facing\attack issue
Hello all,
First let me say I'm an animator by trade, so please excuse my code :) I have an issue with a simple 2d scroller I need help with. I have my hero and he has 2 types of attacks, a melee attack and a ranged attack. Enemies will spawn from behind and in front of the hero character. I use Vector3.Dot to get whether the enemy is behind or not. However when the character passes the origin these values flip. Also if I use the parent of the enemy and the gameObject (rotates to face character) my values are also flipped. If I use the parents of both objects, it seems to work fine but I can never turn to an attacker that is behind the character and deal damage. I am guessing that this might be a "space issue".
The hero and enemies are setup like this
Prefab EmptyGameObject CharacterRig
I move the characters by moving the prefab object. I rotate the characters to look in either direction by rotating the EmptyGameObject.
Have I gone about this the wrong way? I thought about using the character controller but I figured these guys were so simple, I dont need the ability to jump, that not using it would be the better option. It works when the character is in negative x, but when I cross into positive x, it doesn't work because the values have flipped.
I have declared enemy as a JavaScript array, and I populate it with game objects that have a tag of BadGuy. The variable myPar is the parent of the emptyGameobject for the hero.
Here is my code for checking if an enemy is in front or behind.
for(var i=0; i < enemy.length; i++) { if(enemy[i] != null) //check if there are any enemies { var enemyScript : enemyControl; enemyScript = enemy[i].GetComponent(enemyControl); eObj = enemy[i].transform.Find("Enemy"); //check the distnce from the player and verify the enemy is attacking var myDist : float = (Vector3.Distance(myPar.transform.position, enemy[i].transform.position)); var me = myPar.transform.TransformDirection(myPar.transform.position.x, myPar.transform.position.y,myPar.transform.position.z); var whichEnemy = (eObj.transform.position - myPar.transform.position); if(myDist < enemyScript.attackRange && enemyScript.eHealth > 0 ) //if enemy in range deal damage and move back { print(Vector3.Dot(me, whichEnemy)); if((Vector3.Dot(me, whichEnemy)) > 0) { enemyScript.eHealth -= dam; }
}
}
else
{
enemy.RemoveAt(i);
}
}
Any help would be appreciated! Thanks! Alex
Well after some work and I am quite sure jerry rigging I have it working. I just have a check for the origin and handle the exception accordingly. I'm sure there is a better way but this works :)
Your answer
Follow this Question
Related Questions
MoveTowards inside Coroutine 2 Answers
Player isn't affected by AddForce(), Lerp() etc. 1 Answer
Greater than or equal to Vector3 1 Answer
Convert WASD to local rotation 1 Answer
Smooth translation 2 Answers