0

Im using transform.translate to move my game object, the code works fine with a hard coded value (provided i make sure to add f to the end of the float) but when I give it a variable to take that same value from the code doesn't seem to execute, nor does it freeze my unity.

I've tried making the variable a float via (float)Xstep, this results in nothing happening when W is pressed. I modified the code, originally it was setting the 'original X' from the X meaning that everytime X ticked down, orig X did aswell, which while the code did nothing when W was pressed, wasn't an intended result. I don't believe there is a difference between (float).25 and .25f but if there is I haven't found anything on the documentation as to what the equivilent of suffixing an f does

//Original code
public class Player : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W)) {
            StartCoroutine("stepNorth");
        }
    }
    IEnumerator stepNorth() {
        var x = 4;
        while (x > 0)
        {
            gameObject.transform.Translate(0, .25f, 0);
            yield return new WaitForSeconds(.25f);
            x = x - 1;

        }
    }

}
//new code using variable
public class Player : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W)) {
            StartCoroutine("stepNorth");
        }
    }
    IEnumerator stepNorth() {
        var origx = 4;        
        float Xstep = 1 / origx;
        var x = origx;
        while (x > 0)
        {
            gameObject.transform.Translate(0, (float)Xstep, 0);
            yield return new WaitForSeconds((float)Xstep);
            x = x - 1;

        }
    }

}

The end goal of this code is to make a system of movement for a 2d topdown game, made with tiles. The sum of each mini step has to equal one, so that the game object ends up in the center of a tile any time they move. I wanted to simplify this to use variables so that I could test different amounts of "frames" for it more easily.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
cdog1019
  • 9
  • 4
  • 4 is an int, 1 is an int, so it calculates 1 (int division) 4, which is 0, and stores it into Xstep. You should use `float orgix = 4f;` and `float Xstep = 1f / origx;` – Ruzihm Jun 06 '19 at 04:54
  • I'd like to thank you for your extremely quick reply, You actually answered my question before I managed to delete it as I had finally stumbled upon it by dumb luck and fiddling. – cdog1019 Jun 06 '19 at 05:00
  • the `f`s are actually not really neccessary. It's enough to have `float orgix = 4;` or `var orgix = 4f`. Later it already knows that it's a `float` and will use the float devision. – derHugo Jun 06 '19 at 05:37

0 Answers0