I’m making a 2d game and trying to have a unit always follow a unit. If there isn’t enough space between the edge of the camera and the parent transform, I want the child transform to move in front of the parent transform. Then, where the parent moves enough so that there is enough space for the child between the edge of the camera and the parent, I want it to move back behind the parent.
It works perfectly when the parent is facing right. When it’s facing left, the child will always stay in front of the parent.
void Update(){
float y = .25f;
if (Mathf.Abs (cameraBounds.extents.x) - (Mathf.Abs (player.position.x) + playerCollider.bounds.extents.x) <= size.x) {
Debug.Log ("No space!");
float x = Mathf.Sign (-player.position.x) * .5f * transform.parent.right.x;
targetPosition = new Vector2 (x, y);
} else {
Debug.Log ("Space!");
targetPosition = new Vector2 (-.5f * transform.parent.right.x, y);
}
transform.localPosition = Vector2.MoveTowards (transform.localPosition, targetPosition, speed * Time.deltaTime);}