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.