0
votes

Im trying to make the camera movement in Unity but I have a problem, the player will always start with a rotation 0,0,0, even I rotate it in Y before playing.

I the code I rotate the player in Y axis and the camera in X, so the player wont rotate when looking up-down.

Here is the code:

public float cameraSpeed;
//public float smooth = 2;
[Range(0f, 1f)] public float smooth = 0.5f;
Vector2 mouseLook;
Vector2 smoothV;

private Transform cameraTransform;


void Start()
{
    //Inicializamos componentes
    rb = GetComponent<Rigidbody>();
    cameraTransform = Camera.main.transform;

    mouseLook.y = Mathf.Clamp(-cameraTransform.localRotation.x, -75, 50);
    mouseLook.x = transform.localRotation.y;
}

void CameraMovement()
{
    //Declaramos un vector con la direccion del raton
    Vector2 md = new Vector2(InputManager.main.HorizontalMouse(), InputManager.main.VerticalMouse());
    md *= cameraSpeed / smooth;
    smoothV = Vector2.Lerp(smoothV, md, smooth);
    mouseLook += smoothV;

    //Limitamos el angulo de la camara para que no de vueltas
    mouseLook = new Vector2(mouseLook.x, Mathf.Clamp(mouseLook.y, -75, 50));

    //Hacemos que rote la camara en el eje x y el jugador en el eje y
    Camera.main.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
    transform.localRotation = Quaternion.AngleAxis(mouseLook.x  , transform.up);
}
2

2 Answers

0
votes

Because of you haven't keeping rotation value continuously. you started always using mouse rotation that is why so just keep rotation value like

Camera.main.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right) * Camera.main.transform.localRotation;
transform.localRotation = Quaternion.AngleAxis(mouseLook.x  , transform.up) * transform.localRotation;
0
votes

The mouseLook is always 0, 0 in the first frame. So when you do

mouseLook += smoothV;

The first time you have always a value starting from a zero vector.


You should store the initial rotation (and btw also the mainCamera to avoid always getting it via Camera.main) like e.g.

private Transform cameraTransform;

private void Start()
{
    cameraTransform = Camera.main.transform;

    mouseLook.y = MathfClamp(-cameraTransform.localRotation.x, -75, 50);
    mouseLook.x = transform.localRotation.y;
}

Then in your smooth calculation since both components x and y are equal for

md = Vector2.Scale(md, new Vector2(cameraSpeed * smooth, cameraSpeed * smooth));

you could also use a simple float multiplication like

md *= cameraSpeed * smooth;

Then instead of Lerp the x and y component individually you can use

smoothV = Vector2.Lerp(smoothV, md, 1f / smooth);

I would actually recommend for better understanding to rather use

[Range(0f, 1f)] public float smoothFactor = 0.5f;

and then accordingly

md *= cameraSpeed / smoothFactor;
smoothV = Vector2.Lerp(smoothV, md, smoothFactor);