I’m trying to write a C# script that zooms a stationary camera via scroll wheel. I want it so that when a scrolling motion is detected, if the mouse position is over a game object, then the camera rotates towards the game object to look at it and zoom in/out. I’m using Physics.Raycast and having a few problems with accessing the position of the object that is hit for camera.transform.LookAt…
My code so far:
private const int ZoomSpeed = 7;
void Update() {
if(Input.GetAxis("Mouse ScrollWheel") != 0) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit, Mathf.Infinity)) {
camera.transform.LookAt (hit.collider.gameObject.position);
//This doesn't work
}
}
var zoomDelta = Input.GetAxis("Mouse ScrollWheel")*ZoomSpeed*Time.deltaTime;
if (zoomDelta > 0 && Camera.main.fieldOfView >10){
Camera.main.fieldOfView--;
}
if (zoomDelta < 0 && Camera.main.fieldOfView <60){
Camera.main.fieldOfView++;
}
}
Ok, here is the final version of the zoom to mouse cursor script via scroll wheel by using Lerp… This script tries to zoom towards/around the mouse cursor so that the mouse is still on the object/area it was initially pointing at (a bit like Google Maps zoom). The Lerping out is still a little buggy, however. Note that the values are tailored to my game and it sometimes shifts a little off the mouse:
As you can see, you need to provide a distance from the camera for the 3D mouse position.
This is because the mouse position is 2D screen space and obviously the world space is 3D.
A distance of 0 would put your 3D point on the cameras near plane. How to determine the distance you want the 3D point to be is up to you.