- Home /
Why Child's Local z position is changing when I change z of my camera.
I have a scene where I have my background sprite positioned at 10 local unit z under camera. I have a perspective camera. My background is child of my camera. I am changing z of my camera but it's automatically changing z of background. Like when I change my z to -20 camera child background object's z also change to 20 How can I avoid it ?
My Camera Movement / Following script
using UnityEngine;
public class CameraController : MonoBehaviour
{
Vector3 newPos;
public Vector3 camOffSet = Vector2.zero;
public float speed = 2;
Vector3 TargetPos
{
get
{
return CarController.Instance.transform.position;
}
}
void FixedUpdate()
{
if (CarController.Instance != null)
{
newPos = TargetPos + camOffSet;
//if (!CarController.Instance.IsGrounded && CarController.Instance.CanZoomOut)
//{
// float zz = Mathf.Clamp(-10 - newPos.y, -20, -10);
// newPos.z = Mathf.Lerp(transform.position.z, Mathf.Clamp(-10 - newPos.y, -20, -10), speed * Time.deltaTime);
// //newPos.z = zz;
// newPos.x -= zz * 0.2f;
//}
//else
{
newPos.z = Mathf.Lerp(transform.position.z, -10, speed * Time.deltaTime);
}
transform.position = newPos;// Vector3.MoveTowards(transform.position, newPos, speed * Time.deltaTime);
}
}
}
My Bg Move/follow script
public float speed;
Vector3 targetPos = Vector2.zero;
void Update()
{
if (CarController.Instance != null)
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
}
}
How are you checking the child position? transform.position of the child will change of course, because it is the global position while transform.localPosition should still be (0, 0, -10). Also you should have no script on the background at all that is changing the position.
Answer by tormentoarmagedoom · Jan 03, 2018 at 01:08 PM
Hello!
If you change the transform.position of a gameobject, all gameobjects childs will move with it. If the child is not moving where it should, can be for these 2 reasons:
There is another script changing its position
The parent GameObject (the camera) have some scale/rotation value that is making its children move "wrong"
Try it, post some Images of the camera inspector
No, No script is changing position of child. ALso rotation and scale of camera is also not being moved. I am have updated question to attach my code that moves my camera and my bg.