Hello,
Now I facing a problem where my character facing enemy and left click. It doesn't attack the enemy. By the way, I using raycast to detect enemy.
Here are the code, (Hope you guys don't mind the messy code I have).
public class PlayerAttack : MonoBehaviour {
public GameObject target;
public GameObject target1;
public double attackTimer;
public double coolDown;
public RaycastHit hit;
// Use this for initialization
void Start () {
PlayerStats AS = (PlayerStats)target1.GetComponent("PlayerStats");
attackTimer = 0;
coolDown = AS.calculateSpeed();
}
// Update is called once per frame
void Update () {
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height /2, 0));
if(attackTimer > 0)
attackTimer -= Time.deltaTime;
if(attackTimer < 0)
attackTimer = 0;
if(Input.GetMouseButtonUp(0)){
if(attackTimer == 0)
{
if(Physics.Raycast(ray, out hit, 3))
{
Debug.Log("Attack!");
Attack();
attackTimer = coolDown;
}
}
}
}
private void Attack(){
float distance = Vector3.Distance(target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
if(distance < 2.5f)
if(direction > 0)
{
if(target != null)
{
PlayerStats ad = (PlayerStats)target1.GetComponent("PlayerStats");
EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
eh.AdjustCurrentHealth(-ad.attackDamage());
}
}
Please and thank you for solving my problem!
↧