Hello everyone.
So I’m studying game development and right now I want to make an rpg game. I have stats for my player but I don’t really know how to make the damage he does or the damage he takes randomized when the enemy attacks him or when he attacks. I already have a test script where he takes damage when you press a button. Now I want the player to do damage to the enemy when you press a button. This is what I have in my PlayerControls script
//Stats for the player
private int _attack = 6;
private int _defense = 6;
private int _maximumHealth = 100;
private int _maxMP = 100;
private int _luck = 6;
private int _int = 6;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
thanks for your help it’s appreciated.
First, let’s add another property to your character.
private int hitRange = 1;
Then we should determine which button to press in order to attack, We can use if statement for that. Since “Update” function is called per frame, it is the one we should be using to detect input.
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
Attack();
}
}
void Attack()
{
}
Alright, now we are calling “Attack” method each time the player left-clicks. As for Attack method, we should check if the enemy is within our player’s hitRange. If it is, we should make our enemy take damage.
void Attack
{
RaycastHit hit;
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 origin = transform.position
if(Physics.Raycast(origin, forward, hitRange, out hit))
{
if(hit.transform.gameObject.tag == "Enemy")
{
hit.transform.gameObject.SendMessage("TakeDamage", 30);
}
}
}
We used raycasting here, for more information about raycast, visit here.
We basically, checked if we could hit something and that something had the tag “Enemy”. If it was true, We sent them a damage message which in this case enemies must have a script including a method named TakeDamage which would look something like this:
private int health = 100;
void TakeDamage(int damageAmount)
{
health = health - damageAmount;
// We should also check if the health is still greater than 0
// in order to determine whether enemy is still alive or not
if(health < 0)
{
// This enemy is supposed to be dead now.
}
}