Hi,
I have a child object that I would like to translate to the right by a set distance when it enters a trigger. The child is directly in front of its parent which is translating forwards. I would like to be able to move the child to the right by a set distance without affecting the distance between the parent and child (along Z) after the move - that is, I would like the child to continue moving forward with the parent whilst moving to the new position.
What’s happening with my code below is that when the child begins moving to the right it falls behind the parent and stays there. The script for the parent’s forward translation is on the parent object. The movement is currently executed using a mouse key press to simulate the trigger.
Any guidance would be great.
Thanks
public bool moving = false;
private Vector3 PointA;
private Vector3 PointB;
public float time;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
PointA = transform.position;
StartCoroutine(MoveFromTo(PointA, PointB, time));
Debug.Log("Mouse button pressed");
}
}
IEnumerator MoveFromTo(Vector3 pointA, Vector3 pointB, float time)
{
if (!moving)
{
moving = true;
// Move 10 units to the right - better to use Vector3.right ?
Vector3 RightPos = new Vector3(10f, 3, transform.position.z);
float t = 0f;
while (t < 1f)
{
// sweeps from 0 to 1 in time seconds
t += Time.deltaTime / time;
pointB = RightPos;
// set position proportional to t
transform.position = Vector3.Lerp(pointA, pointB, t);
// leave the routine and return here in the next frame
yield return 0;
}
// finished moving
moving = false;
}
}