- Home /
Melee system using raycasting
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!
I would sprinkle some Debug.Log statements in there to find exactly where the issue lies. Does the Attack() method get called at all?
Physics.Raycast returns true when it intersects with ANY collider, not necessarily the target collider you had in $$anonymous$$d (this also means the target needs to have a collider). You should check the collider that got hit by comparing hit.collider.gameObject against your target gameObject.
Note that Input.Get$$anonymous$$ouseButtonUp(0) will not return true until the frame when you release the first mouse button, and will return true for only a single frame. This may be what you want, but I would have expected Input.Get$$anonymous$$ouseButtonDown(0) personally.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Converting Melee Raycast from Java to C# Problems 1 Answer
Player Attack Script. I Need Help! 0 Answers