Hey guys and gals, I am very new to Unity (Day one) and I already have a nice terrain and a player and an enemy. right now it is in first person and I am holding a sword. I have a nice animation built to swing it, and I have it set so if enemy is within max range it takes damage eventually dying.
My problem is that it seems I can not “target” the enemy. When I am clicking and swinging my sword it is going through the enemy and the range is saying it is 10+ away. It seems to have an incredibly small hit box. How can I change it so I can actually hit my enemy?
P.S. My enemy is just a grey cylinder at the moment.
If it’s first-person melee, then I’m assuming the player needs to actually be targeting the enemy, rather than give more leeway like third-person melee where it attacks the closest that you’re facing, right? If that’s the case, you can “target” enemies the same way you would in a standard shooter (performing a raycast going straight forward).
Also, I’d recommend making both the player character and enemies subclasses of a CharacterStats base class (“Character” is already a wrapper class for char in C#). In fact, I take it a step further and make Characters part of a Destructible parent class. That way you can attack a breakable object with the same Attack() function that you’ll attack a character with.
Additionally, I’d recommend having the WEAPONS do the “attacking”, rather than the character. The advantage of this is that it lets both enemies and the player attack with the same weapons, and the only difference is how each one actually triggers that attack (player = input, enemy = AI).
With that said, you can target them like this:
public class Weapon : MonoBehaviour
{
//This base class is really only necessary if you'd like multiple types of weapons, such as both melee and ranged
public float range; //attack distance
public float damage;
public virtual void Attack() {}
}
public class Sword : Weapon
{
public override void Attack()
{
//Ray straight out of the center of the camera
Ray ray = Camera.main.ViewportPointToRay(new Vector3(.5f, .5f, 0));
RaycastHit hit;
if(Physics.Raycast(ray, out hit, range) && !hit.collider.isTrigger && hit.collider.GetComponent<Destructible>() != null)
{
//Replace "Destructible" with the class name for your destructible object/enemy. TakeDamage() should also check if health < 0, emit sounds, etc
hit.collider.GetComponent<Destructible>().TakeDamage(damage);
}
}
}
Then in your Player class, rather than just doing a simple Attack function, you would do:
equippedWeapon.Attack();
If your making a sword then you can check for collision with the blade. In my lastest game, Little World, I use that for blades and swords. That way its also a little more realstic instead of being able to hit something 3 metres away…