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 speed is effecting the starting position

Discussion in 'Scripting' started by AV_Corey, Sep 2, 2016.

  1. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    Hey everyone,

    I'm having a strange issue where my projectile's starting position changes if the speed of the projectile is too high.

    This is the code that controls my projectile movement:
    Code (CSharp):
    1. private IEnumerator moveTo()
    2.     {
    3.         float i = 0f;
    4.         while (i < 9f)
    5.         {
    6.             i += Time.deltaTime * bulletSpeed;
    7.             gameObject.transform.position = Vector3.MoveTowards(transform.position, targetPos, Time.deltaTime * bulletSpeed);
    8.             yield return null;
    9.         }
    10.     }
    If the float bulletSpeed is anything ~10 or higher the starting position of the bullet appears to move slightly off of it's transform (startPos) and it gets worse and worse the higher the bulletSpeed is.

    I'm stumped, does anyone have any ideas? If you need any other information I'm happy to give it.

    Thanks,
    Corey
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    I'm going to take the time to explain how MoveTowards works here, not because you need it, but because this is like the fifth time it's come up in the past week and this is another opportunity to clarify things.

    MoveTowards essentially takes the first position it's given (the origin) and moves it in the direction of the second position (the target) by a given incremental distance. In this case, you're taking "the time between the last frame and this frame" (Time.deltaTime) and multiplying it by speed, which, when the function is done, gives you the origin position moved closer to the target position by something like (.02 * speed units), then you're assigning that result back to the current position. That works great in Update, and makes it framerate independent, because it'll take the same amount of time to reach the target at 30 fps as it will at 60 fps.

    The issue here is that you're applying that change immediately, and if you're instantiating the bullet in the same frame, then immediately moving it X units, then it'll appear to instantiate in that new position. If you want a single frame where movement doesn't happen, to let it "exist" at the origin point for a moment, just toss in a "yield return null;" before the loop as well.
     
    Last edited: Sep 3, 2016
    AV_Corey likes this.
  3. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    (hi again lol) This fixed my issue entirely. Thankyou for the explanation, very helpful :) <3