Search Unity

Somewhat simple math interval problem

Discussion in 'Editor & General Support' started by SkillBased, May 27, 2015.

  1. SkillBased

    SkillBased

    Joined:
    Aug 11, 2014
    Posts:
    141
    Hi.

    This is kind of a general programming question but I'm trying to find a good solution within Unity.

    First, this should be simple. I don't know if i'm missing some simple mathematic concept but I am getting stuck trying to do one simple thing.

    So basically I'm spawning assets (doesn't matter what) whenever a counter reaches a number divisible by a pre-determined number. So, let's say I want it to be every 300 ticks. Every:

    300, 600, 900, 1200... etc we get a spawn. So far so good.

    Now using the same kind of system I wan to destroy that object, say, 50 ticks after it spawns. So, every:

    350, 650, 950, 1250...

    I immediately went to modulo as a solution (same solution I used for spawning) and quickly realized this calculation is going to be a bit more difficult. Here's my eyesore of a hack that isn't even doing the job, but you'll see my reasoning and hopefully bestow on me an elegant solution :)

    Code (CSharp):
    1.         int MultipleFix;
    2.        
    3.         void Start()
    4.         {
    5.             MultipleFix = 1;
    6.         }
    7.         void Update()
    8.         {
    9.             int Timer = GetComponentInParent<PowerUpSpawn>().Timer;
    10.             if (Timer % ((350 * MultipleFix) - (50 * (MultipleFix - 1))) == 0)
    11.             {
    12.                 GameObject.Destroy(this.gameObject);
    13.                 MultipleFix++;
    14.             }
    15.         }
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    You're right to go to modulus when you're searching for certain increments, but the key concept you missed here is an offset. You're still searching for increments of 300, but with an offset of 50.

    if (Timer % 300 == 50)
    returns true for Timer value of 350, 650, 950, etc.
     
  3. SkillBased

    SkillBased

    Joined:
    Aug 11, 2014
    Posts:
    141
    I knew I was missing something ridiculously simple. Thanks!