- Home /
Setting Z transform value of current object in C#
So I'm working a 3rd person camera control script for zooming in an out with the mouse wheel and I'm having trouble setting limits to the zoom. The zoom works just fine. I tried placing the translate lines inside an if statement that used limits as conditions, but that would cause the zoom to actually overshoot and become stuck.
How can I set the Z transform only. I want to evaluate the current transform and if its outside the limits I set, it gets set to the limit.
void Update () {
scrollWheel = Input.GetAxis("Mouse ScrollWheel");
transform.Translate(Vector3.forward * scrollWheel * cameraZoomSensitivity);
if(transform.localPosition.z >= cameraMinimumDistance)/*what goes here???*/;
if(transform.localPosition.z <= cameraMaximumDistance)/*what goes here???*/;
}
Sorry for the newb question.
Answer by robertbu · Jul 15, 2014 at 05:22 AM
In C#, you cannot assign individual components. So you code might be:
void Update () {
scrollWheel = Input.GetAxis("Mouse ScrollWheel");
transform.Translate(Vector3.forward * scrollWheel * cameraZoomSensitivity);
Vector3 pos = transform.position;
pos.z = Mathf.Clamp(pos.z, cameraMinimumDistance, cameraMaximumDistance);
transform.position = pos;
}
Note I've used 'transform.position' rather than 'transform.localPosition'. There may be a valid reason to use transform.localPosition instead, but it is not spelled out in the question.
Answer by Tominator0524 · Jul 15, 2014 at 06:21 AM
Thank you so much for pointing me in the right direction! Your example got me most of the way there. It placed the limits on the z transform, but my y transform would change once the z limit was hit. I added one line to fix this:
void Update () {
scrollWheel = Input.GetAxis("Mouse ScrollWheel");
transform.Translate(Vector3.forward * scrollWheel * cameraZoomSensitivity);
cam = transform.localPosition;
cam.z = Mathf.Clamp(cam.z, cameraMinimumDistance, cameraMaximumDistance);
cam.y = Mathf.Clamp(cam.y, 0.0f, 0.0f);
transform.localPosition = cam;
}
Thanks again.
Since you are clamping 'y' to zero, you can just assign it 0.0 and avoid the function call:
cam.y = 0.0f;
Your answer
Follow this Question
Related Questions
Simple camera zoom function 1 Answer
getting the position of player for the minimap to follow 1 Answer
Pinch zoom 0 Answers
Setting a cube to be exactly size of intersecting camera view plane 1 Answer
GUI.Button child of the camera . 0 Answers