- Home /
Object position flickering
Hey there, I'm new to Unity (and coding in general) and need some help with a script I'm working on.
I'm trying to move the camera forward and backward on the Z axis by pressing E and Q, but only within a certain range. I also have it set up so that if you press R it resets the camera to its original position.
Whenever I run my current script, the camera moves/flickers between two points really quickly. I think it has something to do with using transform.position in two places, but I can't understand why (or how to fix it). Any help would be appreciated!
public class CameraMovement : MonoBehaviour {
Vector3 originalPos;
private float minZ = -1f, maxZ = -2f;
// Use this for initialization
void Start () {
originalPos = new Vector3(0f, 0f ,-1.5f);
}
// Update is called once per frame
void Update () {
Vector3 currentPosition = transform.position;
currentPosition.z = Mathf.Clamp(currentPosition.z, minZ, maxZ);
transform.position = currentPosition;
if (Input.GetKey("e"))
{
transform.position += new Vector3(0F, 0F, (0.1f * (Time.deltaTime * 6f)));
}
if (Input.GetKey("q"))
{
transform.position += new Vector3(0f, 0f, (-0.1f * (Time.deltaTime * 6f)));
}
if (Input.GetKey("r"))
{
transform.position = originalPos;
}
}
}
Answer by hawksandwichgames · Jun 01, 2018 at 07:56 AM
Hey! I think the problem is in the math. -2 is less than -1, but you've set the minimum to -1 and maximum to -2. Try switching the two around and see if the problem still occurs.
Thanks for catching that, it looks like that was the problem after all! :)
Your answer
Follow this Question
Related Questions
moving random objects to random positions 1 Answer
GUI item with object position+dimensions 0 Answers
Object isnt where its supposed to be when selected 0 Answers
Move hit.point 1 Answer