Problem with instantiate script

Hello!

I’ve got a problem with my spawn script which i just cant figure out. The point of the script is to spawn platforms aligned perfectly next to each other, without any gap between. The “SpawnDistance” variable sets the distance on how often the platforms should spawn, for example if its set to 20, then they will spawn every 20 position. And the platforms have to be 20 units wide to be aligned. The script is attached to an empty game object that get its position from the player which is constantly moving with use of:

transform.Translate(Vector2.right * speed * Time.deltaTime);

Now on to the problem… On lower speeds this is working perfectly and they align like they should, but when you go a bit faster, then the errors start to appear. I Made a debug to get the positions on where they actually spawn at, as you can see on the image: imgur this sometimes happens. The extra number added to some of the positions. The frequency of this happening depends on the players speed, at some speeds this doesnt happen at all. And i just dont know why this happens… It doesnt seem to be a rounding problem.

Any ideas?

var obj : GameObject[];
var player : Transform;
private var xmin = 0;
var SpawnDistance = 20;

function Spawn() {
	var temp = Mathf.FloorToInt(player.position.x/SpawnDistance);
	transform.position.x = Mathf.FloorToInt(transform.position.x);

	if (temp > xmin){
		for(var i = xmin; i < temp; i++){
			Instantiate (obj [Random.Range (0, obj.Length)], transform.position, Quaternion.identity); 
		}
	    xmin = temp;
	    Debug.Log(transform.position.x);
	}
}

I’m not quite seeing why the spawner needs to move - why not just use the player’s position to spawn the… whatever you’re spawning?

Anyways, With a speed of 55, you’re moving 55 units every second. With fixed timestep set to the default (.02), you’re running FixedUpdate 50 times each second. This means that for every FixedUpdate, you move the player 1.1 units. Thus, every tenth fixedUpdate, the floor of the current position will be two more than the floor of the last position. That means that at some regular intervals, you’ll skip over a “whole” 20.

To fix this, instead of spawning the thing you’re spawning at the rounded player position when the player has moved spawndistance, spawn it at a point that’s exactly 20 away from the last spawn point, in the direction of the player.