1
votes

My app (using Unity 2017.3.1f1) is set up like this:

  • The perspective camera is inside the "player" object (collisions are disabled) and also a child of it (to get a 1st person view)
  • The camera has a "MouseLook" script (I changed a few things in Unity's default one) that keeps the cursor locked and hidden in the middle of the screen (Cursor.lockState = CursorLockMode.Locked & Cursor.visible = false)
  • The "player" has a general "input" script and a movement script: If wasd are pressed, these key presses move the player object, which also makes the camera move

What I want to achieve:

  • Use the scroll wheel on the mouse to move towards the point the camera is looking at or away from it, independent if there's an object.
  • I do NOT want to change the FOV/scale
  • It's not necessary to use Lerp, I just want to move the player a step towards the target position every frame the mouse wheel is used

What I've tried:

1a. In the general input script:

if(Input.GetAxis("Mouse ScrollWheel") != 0) {
    transform.Translate(0,0,Input.GetAxis("Mouse ScrollWheel") * 200);
}

1b: In the general input script:

if(Input.GetAxis("Mouse ScrollWheel") != 0) {
    transform.position += transform.forward * Input.GetAxis("Mouse ScrollWheel") * 200;
}

Both work the same but only move the player/camera on the same y level, even when looking down/up. transform.up always outputs "(0.0, 1.0, 0.0)", so there's no point incorporating that.

2.A new script on the camera (source):

public class ScrollToZoom : MonoBehaviour {
    public GameObject player;

    void Update () {
        if(Input.GetAxis("Mouse ScrollWheel") != 0) {
            RaycastHit hit;
            Ray ray = this.transform.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
            Vector3 desiredPosition;

            if(Physics.Raycast(ray,out hit)) {
                desiredPosition = hit.point;
            } else {
                desiredPosition = transform.position;
            }
            float distance = Vector3.Distance(desiredPosition,transform.position);
            Vector3 direction = Vector3.Normalize(desiredPosition - transform.position) * (distance * Input.GetAxis("Mouse ScrollWheel"));

            transform.position += direction;
        }
    }
}

This doesn't work at all because "direction" is always (0,0,0) because the mouse cursor is locked (which I can't/won't change).

How do you incorporate the rotation around the x-axis (I clamp it to +/- 90° in the "MouseLook" script) in this?

1

1 Answers

1
votes
if(Input.GetAxis("Mouse ScrollWheel") != 0) {
    transform.localPosition += Vector3.forward * Input.GetAxis("Mouse ScrollWheel") * 200;
}

Should work. transform.position will refer to the world position regardless of where the object is facing.