- Home /
Problem with combat.
So I have this specific problem. I'm following BurgZergArcade tutorials, but I wanted to implement them to something of my own. (Think 2.5D platformer) So the problem is as follows: When attacking from the left everything is fine. I hit the target when facing it and missing when facing away, but when hitting from the right side I can hit it no matter if I'm facing the enemy or not.
using UnityEngine;
using System.Collections;
public class PlayerAttack : MonoBehaviour {
public GameObject target;
public float attackTimer;
public float cooldown;
// Use this for initialization
void Start () {
attackTimer = 0;
cooldown = 1.0f;
}
// Update is called once per frame
void Update ()
{
if(attackTimer > 0)
{
attackTimer -= Time.deltaTime;
}
if(attackTimer < 0)
{
attackTimer = 0;
}
if (Input.GetKeyUp(KeyCode.F))
{
if(attackTimer == 0)
{
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);
Debug.Log(direction);
Debug.Log(distance);
if(distance < 3)
{
if(direction >= 0)
{
EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
eh.AdjustCurrentHealth(-10);
}
}
}
}
problem seems to be that "direction" is exactly 0 when attacking from left or right, if player is looking right. Any advice?
Answer by EHogger · Aug 02, 2013 at 09:39 PM
If direction is 0 then dir and transform.forward are perpendicular. Your model is probably rotated wrong. Check that the blue axis is actually pointing forward.
Thank you so much for the answer! Now i'm feeling kinda stupid for not figuring that out, but at least it's working :P