Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

projectile lagging behind target

Discussion in 'Scripting' started by Sajid, Mar 12, 2015.

  1. Sajid

    Sajid

    Joined:
    Mar 12, 2011
    Posts:
    199
    Hey all, I have this code attached to my projectile that gets instantiated by a turret:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class turretBullet : MonoBehaviour {
    5.     public GameObject explosion;
    6.  
    7.     private Vector3 myTarget;
    8.     private float myFireSpeed;
    9.  
    10.    
    11.     // Update is called once per frame
    12.     void Update () {
    13.         transform.position = Vector3.Slerp(transform.position, myTarget,
    14.                                            myFireSpeed * Time.deltaTime);  
    15.     }
    16.  
    17.     void setTarget(Vector3 inTarget)
    18.     {
    19.         myTarget = inTarget;
    20.  
    21.     }
    22.  
    23.     void setSpeed(float inSpeed)
    24.     {
    25.         myFireSpeed = inSpeed;
    26.     }
    27.  
    28.     void OnTriggerEnter(Collider other)
    29.     {
    30.         if(other.tag == "Enemy")
    31.         {
    32.             other.SendMessage("receiveDamage", 5);
    33.             Instantiate(explosion, transform.position, transform.rotation);
    34.             Destroy(gameObject);
    35.         }
    36.     }
    37. }
    38.  
    Now, this works fine when the target is standing still, but once it starts moving, the shots somehow miss and end up going off into empty space instead of following the enemy until they it it. I don't understand how that could happen, because the transform.position is always going to Slerp towards the target until it hits it, so I don't get why it stops.


    Any insight into this?
     
  2. Buddy_Redmond

    Buddy_Redmond

    Joined:
    Aug 30, 2014
    Posts:
    23
    My best guess would be that you only set myTarget once. This would cause the projectile to slerp to the position where the target was when the projectile was fired, not its current position
     
  3. Sajid

    Sajid

    Joined:
    Mar 12, 2011
    Posts:
    199
    OH! I'm so stupid. I should send the projectile a gameObject instead of a vector3. I don't know why I did that
     
  4. Sajid

    Sajid

    Joined:
    Mar 12, 2011
    Posts:
    199