So I have this script, I put two debug.logs in and the the first one calls everytime but the second one never seems to call, is there something wrong with my script?
function mAttack(){
Debug.Log("Melee Attack");
var hit : RaycastHit;
if(attack){
if(Physics.Raycast(transform.position, Vector3.forward, hit, mRange)){
if(hit.collider.tag == "Player"){
Debug.Log("Attacked");
var pScript = hit.collider.GetComponent(Player);
pScript.LoseHealth(damage);
attack = false;
}
}
}
WaitForSeconds(animation["Attack"].length);
attack = true;
}
I added more Debug.Log statements to your code. You should be able to find out what is wrong with it.
function mAttack()
{
Debug.Log("Melee Attack");
var hit : RaycastHit;
if(attack)
{
if(Physics.Raycast(transform.position, Vector3.forward, hit, mRange))
{
if(hit.collider.tag == "Player")
{
Debug.Log("Attacked");
var pScript = hit.collider.GetComponent(Player);
pScript.LoseHealth(damage);
attack = false;
}
else
{
Debug.Log("Did not hit a player (is tag setup for player?)");
}
}
else
{
Debug.Log("Raycast did not hit anything");
}
}
else
{
Debug.Log("attack is false");
}
WaitForSeconds(animation["Attack"].length);
attack = true;
}
Ok I got it working finally but now there’s a problem, everything works but only if I’m standing right in front of the enemy and not anywhere else, so if I’m standing behind his original facing direction even if were both facing each other, it doesn’t recognize it, it’s like the raycast is based of like the vector3.forward of the world and not the local vector3.forward. I have no idea why, here’s the revised script.
I was doing that but there was something messed up with the model that made the raycast go in reverse so I added an empty gameobject (began as a cube so I could see it’s position), to raycast from so that it went the right way.
You may try to use the TransformDirection function which transform direction from a local space to world space. Also, draw ray line to see what has been hit. For example,
Note that transforms have a .forward value already - you don’t need to use TransformDirection( Vector3.forward) in this case; you can just set fwd = transform.forward.
Transforms also have a .right and .up for your programming pleasure.
I think that they have different meanings. Quoted from the Unity Script Reference:
transform.TransformDirection(Vector3.forward)
Transforms direction from local space to world space. This operation is not affected by scale or position of the transform. The returned vector has the same length as direction.