My script allows for a ping pong movement to begin after a collision with a trigger, however the object keeps appearing at different positions within the max and minimum constraints. I would like for the gameobject to begin its movement from where I have placed it.
public class BoxMoveScript : MonoBehaviour
{
public float min = 2f;
public float max = 3f;
public float n;
bool TimerStarted = false;
// Start is called before the first frame update
void Start()
{
min = transform.position.x;
max = transform.position.x + n;
}
// Update is called once per frame
void Update()
{
if (TimerStarted)
{
moveBox();
}
}
void moveBox()
{
transform.position = new Vector3(Mathf.PingPong(Time.time * 2, max - min) + min, transform.position.y, transform.position.z);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3)
{
if (!TimerStarted)
{
TimerStarted = true;
}
}
}
If I correctly understand what you are trying to achieve, you should assign min and max inside of OnTriggerEnter2D instead of in Start. This way, the position at the moment of collision is taken into account rather than the start position.
I’ve renamed some variables, the one function and changed visibility to match my understanding of the script. Generally speaking, your scripts shouldn’t expose more data than necessary and you can use the SerializedField attribute to show non-public fields in the inspector. The variable named n is now called pingPongWidth. This needs to be configured through the inspector, so it should have a descriptive name!
I’ve introduced a new variable startTime which stores Time.time at the moment of collision. One could describe this as “resetting the timer”, so there is no initial jump when the PingPong movement starts. The first Update when PingPongMove is called, you want to get xMin or something reasonably close, which means t should be close to 0f.
I hope this makes sense. I haven’t tested the script to be honest, but I’m pretty sure it should do the trick.