Search Unity

Problem with raycast really need help!! (URGENT)

Discussion in 'Scripting' started by MrTeamTactical, Aug 27, 2014.

  1. MrTeamTactical

    MrTeamTactical

    Joined:
    Aug 27, 2014
    Posts:
    2
    So im right in the middle of a series of tutorial videos and i cant move on until i fix this problem. What it is, is a survival game and iv been following instruction on using raycaster to see the distance between the player and an object so that i can then set it to attack the enemy when your within a certain distance. However i'v done what he said as to how to do this and its just saying the distance is 0 no matter what i do. When he was showing it he would click attack and it would show the distance of whatever object you where looking at while attacking. Any ideas as to what it is?

    #pragma strict

    var TheDammage : int = 50;
    var Distance : float;
    var MaxDistance : float = 1.5;
    var TheSystem : Transform;

    function Update ()
    {
    if (Input.GetButtonDown("Fire1"))
    {
    //Attack animation -
    animation.Play("Attack");

    }
    // if (TheMace.animation.isPlaying == false)
    // {
    // TheMace.animation.CrossFade("Idle");
    // }
    //
    // if (Input.GetKey (KeyCode.LeftShift))
    // {
    // TheMace.animation.CrossFade("Sprint");
    // }
    //
    // if (Input.GetKeyUp(KeyCode.LeftShift))
    // {
    // TheMace.animation.CrossFade("Idle");
    // }
    }
    function AttackDammage ()
    {
    //Attack function
    var hit : RaycastHit;
    if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit))
    {
    Distance = hit.distance;
    if (Distance < MaxDistance)
    {
    hit.transform.SendMessage("ApplyDammage", TheDammage, SendMessageOptions.DontRequireReceiver);
    }
    }
    }
     
  2. Karwler

    Karwler

    Joined:
    Aug 25, 2014
    Posts:
    18
    Try putting that into the Update function.
    Code (JavaScript):
    1. if(Input.GetButtonDown("Fire1"))
    2.     {  
    3.         TheMace.animation.Play("Attack");
    4.         var hit : RaycastHit;
    5.         if(Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit))
    6.         {
    7.             Distance = hit.distance;
    8.             if(Distance <= MaxDistance)
    9.             {
    10.                 hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);
    11.             }
    12.         }
    13.     }
    And you need a Transform variable called TheMace in order to be able to play the animations. Make also sure all objects in the scene are in the correct position. (It's damage not dammage)