- Home /
Question by
Astraphobia95 · Nov 16, 2017 at 03:56 PM ·
unity 2d
Detecting when a 2D object passes a point on a consistent basis
I have some code to re-position my background sprite once it moves past a certain threshold, that looks like this:
//Update runs once per frame
private void FixedUpdate()
{
//Check if the difference along the x axis between the main
Camera and the position of the object this is attached to is greater
than groundHorizontalLength.
if (transform.position.x < -groundHorizontalLength)
{
Debug.Log("Pos: " + transform.position.x + " Length: " + -
groundHorizontalLength + " Time: " + Time.deltaTime);
//If true, this means this object is no longer visible and we can
safely move it forward to be re-used.
RepositionBackground();
}
}
//Moves the object this script is attached to right in order to create
our looping background effect.
private void RepositionBackground()
{
//Move this object from it's position offscreen, behind the player, to
the new position off-camera in front of the player.
transform.position = (Vector2)transform.position + groundOffSet;
}
I've noticed that the condition gets met when the object is in slightly different positions each time (~0.1 on the X axis), which sometimes ends up leaving an unwanted gap between my two sprites.
Is there a way I can make the condition trigger on a more consistent basis, or an alternative way of triggering the re-position?
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612142929im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiated object not showing in scene or hierarchy 2 Answers
I have code related to adding audio. 0 Answers
WHY UNITY HAVE THIS PROBLEM ? 0 Answers