Search Unity

Feedback Script for fixed camera ( I'm new in programing)

Discussion in 'Scripting' started by equietum, Dec 12, 2023.

  1. equietum

    equietum

    Joined:
    Dec 9, 2023
    Posts:
    1
    Hello, I'm new to programing and I'm trying to script a very concrete type of camera.

    I need a fixed camera in the z axis that rotates on his axis. That can be moved with WASD only in the X and Y.
    With a limiter on the movement on X and Y.

    Thanks to everyone that is willing to give any davice.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5.  
    6. public class CameraRotateScript : MonoBehaviour
    7. {
    8.     [Header ("Camera Settings")]
    9.     public float CameraRotation;
    10.     public float CameraSpeed;
    11.  
    12.     private float x;
    13.     private float y;
    14.  
    15.     public float sensitivity;
    16.     private Vector3 rotate;
    17.  
    18.     // Start is called before the first frame update
    19.     void Start()
    20.     {
    21.         Cursor.lockState = CursorLockMode.Locked;
    22.     }
    23.  
    24.     // Update is called once per frame
    25.     void Update()
    26.     {
    27.        
    28.  
    29.         y = Input.GetAxis("Mouse X");
    30.         x = Input.GetAxis("Mouse Y");
    31.         rotate = new Vector3(x, y * sensitivity, 0);
    32.         transform.eulerAngles = transform.eulerAngles - rotate;
    33.  
    34.    
    35.  
    36.     }
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,882
    Unity has Cinemachine. It's pretty easy to lock an axis with it, keep it confined to an area, and so on. I would say it's even less of a learning curve than doing this by scripting because you can experiment at runtime with all the different settings, eg you get instant feedback.
     
    Kurt-Dekker and Ryiah like this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,688
    +1 for Cinemachine... seriously! Especially for new programmers.

    Camera stuff is pretty tricky... you may wish to consider using Cinemachine from the Unity Package Manager.

    There's even a dedicated forum: https://forum.unity.com/forums/cinemachine.136/

    If you insist on making your own camera controller, the simplest way to do it is to think in terms of two Vector3 points in space: where the camera is LOCATED and where the camera is LOOKING.

    Code (csharp):
    1. private Vector3 WhereMyCameraIsLocated;
    2. private Vector3 WhatMyCameraIsLookingAt;
    3.  
    4. void LateUpdate()
    5. {
    6.   cam.transform.position = WhereMyCameraIsLocated;
    7.   cam.transform.LookAt( WhatMyCameraIsLookingAt);
    8. }
    Then you just need to update the above two points based on your GameObjects, no need to fiddle with rotations.