Gaps between segments in repeating background
Hey all, first post here. I've been running into a problem with my continuous background script - the script instantiates at a fixed location a random background 'segment' from a group of segments every time a background segment moves the length of its collider (I have no idea if this is the best way to do this). I have a game boundary with OnTriggerExit destroying these segments as they leave in another script.
My problem is, at seemingly random intervals (I've tested using only one segment repeated) there is a small gap between segments. The gaps are seemingly random sizes, and they're not always there.
Due to the random nature I don't feel colliders are to blame as they are uniform lengths. I tried using InvokeRepeating (as shown in my code) to call the script more frequently (I don't know if this works). I first tried using void Update.
The following code is attached to every map segment.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RepeatingBackground : MonoBehaviour {
public GameObject[] mapSegments;
private BoxCollider mapCollider;
private float mapSegmentLength;
private float distanceTravelled = 0;
Vector3 lastPosition;
public bool spawnable;
void Start () {
mapCollider = GetComponent<BoxCollider> ();
mapSegmentLength = mapCollider.size.z;
lastPosition = transform.position;
spawnable = true;
Mover mover = GetComponent<Mover> ();
mover.enabled = true;
InvokeRepeating ("CheckDistance", 0.0f, 0.01f);
}
public void CheckDistance () {
distanceTravelled += Vector3.Distance (transform.position, lastPosition);
lastPosition = transform.position;
if (distanceTravelled >= mapSegmentLength) {
Debug.Log ("Distance Reached");
if (spawnable == true) {
spawnable = false;
distanceTravelled = 0;
SpawnMapSegment ();
Debug.Log ("Segment spawned");
}
}
}
public void SpawnMapSegment () {
GameObject mapSegment = mapSegments[Random.Range (0, mapSegments.Length)];
Vector3 spawnPosition = new Vector3 (-10.27f, -1.0f, 44.0f);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (mapSegment, spawnPosition, spawnRotation);
}
}
Any Ideas would be appreciated.
Try using Bounds.size for setting mapSegmentLength ins$$anonymous$$d of size.