I want a c# script so when I hold right click it zooms in a little and when you stop holding right click it goes back to its original position.
Asked
Active
Viewed 227 times
-1
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 06 '22 at 10:45
1 Answers
0
You would first want to store the original camera z distance. (As I assume you want it to go forward in the z direction). Then you would want to have a float for the amount of tome zoom was held down. (Increase it when zooming, and decrease it when you dont click it). Also have a target z, so it doesn't go too far
public float startZ;
public float targetZ;
public float zoomInSpeed;
public float zoomOutSpeed;
float heldDownTime;
float originalZ;
void Start()
{
startZ = transform.position.z;
}
void Update()
{
if (Input.GetKey(KeyCode.Mouse0))
{
heldDownTime += Time.deltaTime * zoomInSpeed;
}
else
{
heldDownTime -= Time.deltaTime * zoomOutSpeed;
heldDownTime = Mathf.Clamp(heldDownTime, 0, Mathf.Infinity);
}
float smoothed = System.Math.Tanh(heldDownTime);
Vector3 pos = transform.position;
transform.position = new Vector3(pos.x, pos.y, startZ + smoothed * (targetZ - startZ));
}
I basically get the time held down, then I smooth it out, so it doesn't zoom to far forward.
Let me know in the comments if you get any errors!

gbe
- 1,003
- 1
- 7
- 23
-
Where's the class declaration? Does it need to inherit from anything in particular? Unity isn't JavaScript. – Aug 30 '22 at 09:07
-
1@MickyD Oh yes, put it in a class and inherit MonoBehaviour. This should just go inside the script. – gbe Aug 30 '22 at 22:34
-
No worries. I've noticed _alot_ of Unity developers tend to just post methods on SO (questions and answers) and not related `public class xxxx : MonoBehaviour`. Dunno why. Too busy making games I suspect. Don't blame them. :) – Aug 31 '22 at 01:55
-
@MickyD Yeah, I guess so, it takes a lot of time to click the space bar to indent a lot, lol. – gbe Aug 31 '22 at 04:27