Search Unity

Raycasting Look at target issue

Discussion in 'Scripting' started by nera8, Sep 14, 2012.

  1. nera8

    nera8

    Joined:
    Sep 14, 2012
    Posts:
    2
    hey guys,

    Ive got this piece of code here which, what im trying to do is have the turret which the script is on, follow the target ("Player1") when it is in range of the raycast which is on the turret. At the moment the raycast works to the extant that the hit test is fine but the locking on the target and rotation isnt would really appreciate some help thanks ;)

    #code
    var LookAtTarget : Transform;
    var rotate;
    var rotationDamp = 2.0;
    var distanceToPlayer;
    var range = 100.0;
    var hit : RaycastHit;
    var right;
    var target : Transform;


    function Update () {

    right = transform.TransformDirection(Vector3.right);

    distanceToPlayer = Vector3.Distance(LookAtTarget.position, transform.position);

    if(distanceToPlayer <= range)
    {
    if(LookAtTarget)
    {
    rotate = Quaternion.LookRotation (LookAtTarget.position - transform.position);
    }
    }

    if(Physics.Raycast(transform.position,right,hit,range))
    {
    if(hit.collider.gameObject.tag == "Player1")
    {
    shoot();
    }
    }

    else {
    rotate = Quaternion.identity;
    transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * rotationDamp);
    Debug.DrawRay(transform.position,right * range, Color.red);
    }

    }

    function shoot() {

    Debug.Log("shoot at player" + Time.time);

    }

    function Awake() {

    LookAtTarget = GameObject.FindWithTag("Player1").GetComponent(Transform);

    }
    #code
     
  2. roger0

    roger0

    Joined:
    Feb 3, 2012
    Posts:
    1,208
    Looks like there is a mistyped space here in the code

    Code (csharp):
    1.  
    2. function Awake() {
    3.  
    4. LookAtTarget = GameObject.FindWithTag("Player1").GetComponent(Tra nsform);
    5.  
    6. }
    perhaps this could be it?
     
  3. Loius

    Loius

    Joined:
    Aug 16, 2012
    Posts:
    546
    Please use [ code ][ /code ] tags for code.

    You're setting rotate to Quaternion.identity immediately before rotating. That doesn't seem right.

    Edit: The space is appearing because the forum doesn't allow "long words"; it adds spaces in between to separate them.

    For instance, this is a bunch of I's:

    IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

    Forum added a space for me. [ code ] tags allow for longer words.
     
  4. nera8

    nera8

    Joined:
    Sep 14, 2012
    Posts:
    2
    @Loius thanks alot for the advice bro! and it works fine now thank you very much :)