I'm making a 3D village management sim, and when things get crazy, I like to be able to zoom in on the action in a specific region.
This camera control script looks for horizontal and vertical axis inputs (WASD and arrow keys) to allow the player to pan around. It also watches the mouse scrollwheel to allow the player to raise and lower the camera.
Just drop it on your Main Camera
gameobject in your scene, and you're good to go.
The basic pattern is:
- if input
- create a new
Vector3(x, y, z)
using the target inputs-
x
andz
for pan,y
for zoom, the rest0
-
- multiply the
Vector3
by some predefined speed - add the new
Vector3
to the position of the camera transform
- create a new
I've inverted the mouse scrollwheel input so that scrolling up zooms in and scrolling down zooms out.
using UnityEngine;
public class CameraController : MonoBehaviour {
private float moveSpeed = 0.5f;
private float scrollSpeed = 10f;
void Update () {
if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0) {
transform.position += moveSpeed * new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
}
if (Input.GetAxis("Mouse ScrollWheel") != 0) {
transform.position += scrollSpeed * new Vector3(0, -Input.GetAxis("Mouse ScrollWheel"), 0);
}
}
}
Top comments (6)
Hey Matthew,
by adding movement in inconsistent loop, Update in this case, clients with higher FPS are more swift and less smooth. To counter the FPS differences, you could do two things:
Use Time.deltaTime
deltaTime is duration of lastFrame, if you multiplay any value what is based on FPS loops (Update), you'll have consistent results on different frame rates. Check the documentation for it. Usually your moveSpeed or scrollSpeed have to be 10 times bigger.
Apply the movement in consistent loop
FixedUpdate is a loop for physics engine and it runs constant 60 fps. The FPS of the game don't affect the frame rate of FixedUpdate. But the inputs as keystrokes and mouse wheel is detected in Update loop, so to not miss key strokes, you have to do it like so:
I always wonder which is more robust solution.
Happy coding!
Probably best not to instantiate anything in your Update loop.
Good point!
Hello, please change
all int to float;
Ah, thank you :)
Thanks for the tip on FixedUpdate! I hadn't used that before.