Custom Looking Script

I don’t really know how to explain this but ill try my best. I have the default looking script your provided with when creating a new project but I want to somehow customize it.
Instead of having the script make the player look all over the place I want it to only look about 20 degrees up, down, left and right so you can really see what’s behind you or in line with you. Please can anyone help me with this?

The problem here is that the default looking script actually rotates the player- so you can't look behind you, but you can still turn around. Is your player on rails? Or are there other controls for turning?

1 Answer

1

I think you can managed this with the following idea:

  1. read the mouse pos from Input class. http://unity3d.com/support/documentation/ScriptReference/Input.GetAxis.html

  2. add the deltaspeeds of the
    mouseinput into two variables
    (X-sideways and Y-updown)

  3. check the resulting two variables for
    above or below min and max on both
    directions.

This should be fairly simple to put into the camera as a single script.
To update the cameraobject, you use transform.position = new Vector3(x,y,z); for angles. 0,0,0 is streight forward as a standing person. X rotation is pitch/up/down, Y rotation is around your own axis if standing (called Yaw in airplanes)

so use the two variables on X and Y rotation.

Update

The link I gave you even contained the answer, more or less:

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    public float horizontalSpeed = 2.0F;
    public float verticalSpeed = 2.0F;
    void Update() {
        float h = horizontalSpeed * Input.GetAxis("Mouse X");
        float v = verticalSpeed * Input.GetAxis("Mouse Y");
        transform.Rotate(v, h, 0);
    }
}

Now we just need to replace the last line (transform.Rotate) + add a few min/max IF structures

if(v< -45) v=-45;
if(v> 45) v=45;

if(h< -45) h=-45;
if(h> 45) h=45;

transform.position = new Vector3(v,h,0);

You could even clean up the IF structure by using the Mathf.Clamp(value, min, max); function, but I’ll leave that part up to you now.
http://unity3d.com/support/documentation/ScriptReference/Mathf.Clamp.html

oooh! I almost forgot, you need to move the two h and v variables up into the class outside Update function. Otherwise they will not contain the current direction of your view.