Problem with camera (864280)

Hello! I watched this tutorial on how to make a camera follow an object, and whenever it hits another object it uses raycast to reposition (with layers of collision I think), but a few errors came up:
-whenever the character looks towards the camera, it goes at its feet
-when I don’t move, same thing

I’m very inexperienced to unity, so I still can’t understand everything going on in codes.
Thank you for your time!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraManager : MonoBehaviour
{
    InputManager inputManager;


    public Transform targetTransform; //object camera will follow
    public Transform cameraPivot;      //object cam uses to pivot
    public Transform cameraTransform;
    public LayerMask collisionLayers;
    private float defaultPosition;
    private Vector3 cameraFollowVelocity = Vector3.zero;
    private Vector3 cameraVectorPosition;

    public float cameraCollisionOffset = 0.2f;
    public float minimumCollisionOffset = 0.2f;
    public float cameraFollowSpeed = 0.2f;
    public float cameraLookSpeed = 2;
    public float cameraPivotSpeed= 2 ;

    public float cameraCollisionRadius = 0.5f;

    public float lookAngle;  //Cam up down
    public float pivotAngle;  //Cam left right
    public float minimumPivotAngle = -35;
    public float maximumPivotAngle = 35;

    void OnDrawGizmosSelected()
    {
        // Draws a 5 unit long red line in front of the object
        Gizmos.color = Color.red;
        Vector3 direction = transform.TransformDirection(Vector3.forward) * 5;
        Gizmos.DrawRay(transform.position, direction);
    }



    private void Awake()
    {
        inputManager = FindObjectOfType<InputManager>();
        targetTransform = FindObjectOfType<PlayerManager>().transform;
        cameraTransform = Camera.main.transform;
        defaultPosition = cameraTransform.localPosition.z;
    }
    
    private void FollowTarget()
    {
        Vector3 targetPosition = Vector3.SmoothDamp(transform.position,targetTransform.position,ref cameraFollowVelocity,cameraFollowSpeed);
        transform.position = targetPosition;
    }

    public void HandleAllCameraMovements()
    {
        FollowTarget();
        RotateCamera();
        HandleCameraCollisions();
    }

    private void RotateCamera()
    {
        Vector3 rotation = Vector3.zero;
        Quaternion targetRotation;
        lookAngle = lookAngle + (inputManager.cameraInputX * cameraLookSpeed);
        pivotAngle = pivotAngle - (inputManager.cameraInputY * cameraPivotSpeed);
        pivotAngle = Mathf.Clamp(pivotAngle,minimumPivotAngle, maximumPivotAngle);

        rotation = Vector3.zero;
        rotation.y = lookAngle;
        targetRotation = Quaternion.Euler(rotation);
        transform.rotation = targetRotation;

        rotation = Vector3.zero;
        rotation.x = pivotAngle;
        targetRotation = Quaternion.Euler(rotation);
        cameraPivot.localRotation = targetRotation;
    }

    private void HandleCameraCollisions()
    {
        float targetPosition = defaultPosition;
        RaycastHit hit;
        Vector3 direction = cameraTransform.position - cameraPivot.position;
        direction.Normalize();

        if (Physics.SphereCast
(cameraPivot.transform.position,cameraCollisionRadius, direction, out hit, Mathf.Abs(targetPosition), collisionLayers))
        {
            float distance = Vector3.Distance(cameraPivot.position,hit.point);
            targetPosition =- (distance - cameraCollisionOffset);
        }

        if (Mathf.Abs(targetPosition) < minimumCollisionOffset)
        {
            targetPosition = targetPosition - minimumCollisionOffset;
        }
        cameraVectorPosition.z = Mathf.Lerp(cameraTransform.localPosition.z, targetPosition, 0.2f);
        cameraTransform.localPosition = cameraVectorPosition;
       
    }
}

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

Otherwise, if you wish to debug what you have above, here are some techniques you can bring to bear:

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

I put what you said to test, and tried to slowly strip things off to see what was causing the problem. It turns out everything works if I don’t put the default layer in the layers collider. I can walk straight to the camera without it resetting it’s position. I’m pretty sure it has to do with the defaultPosition. Thank you a lot i’ll keep digging into it.

Oh interesting! This code does seem suspect:

Remember the Z is the direction the camera is looking, like down your nose, straight ahead and back. Is that the position you want to capture?

If you are looking around the compass in all directions that is around the Y axis, which is slide up and down.

If you are raising your head to the sky or looking at the floor, that is X axis, which is slide left / right.


What I’m trying to do is this. P is the player, W is a wall with a collider and C the camera. there is a constant ray between the player. If the ray hits something, we need the camera to be repositionned in front of the wall, with a slight offset. Is there a way for me to change the coords of the camera to the position of the cross minus an offset so that it doesn’t stick to the wall?

Oh yeah, I think you def wanna look at Cinemachine… I think it has ways of “keeping object in sight” but I haven’t used that feature enough. Here’s just the first thing I found on goog:

https://discussions.unity.com/t/733571

Sounds like there’s a lot of possible ways to do it in Cinemachine, as it turns out a lot of games want to keep the player in sight!

After a few videos I managed to have a working camera! I’ve also tried to make an FPS one, but it looks slightly wobbly. I couldn’t find much tutorials on that, could you help me out?

An FPS one what? FPS doesn’t really have any camera work: you control it directly.

If you would prefer something more full-featured here is a super-basic starter prototype FPS based on Character Controller (BasicFPCC):

https://discussions.unity.com/t/855344

That one has run, walk, jump, slide, crouch… it’s crazy-nutty!!

I meant FPS test project my bad here! I’m trying to get experience in both first and third person. I’ll follow along the video you sent me thank you a lot!

The FPS I found earlier gave me some pretty good results, so I’ve came back to the TP one. But yet again a problem comes up :slight_smile:

As you can see on this video, The camera follow along quite nicely, but there’s one issue. When I move my character, and rotate the camera, the model doesn’t follow what the camera is poiting to. Is it something Cinemachine can deal with?

I’m sorry if some sentences don’t sound too awesome, I’ll blame it on the irregular verbs I didn’t learn in middle school.

Cinemachine deals with cameras. What you are showing above is the controls not being properly mapped to view direction, so that lives outside of what Cinemachine cares about.

You need to rotate your inputs by the heading of the camera, which you can get from the camera’s transform.

You can see it being done in the DemoCameraRotatedControls scene in my proximity buttons project. Specifically it is this script:

https://github.com/kurtdekker/proximity_buttons/blob/master/proximity_buttons/Assets/DemoCameraRotatedControls/RotatedControlsPlayerController.cs

Around lines 124 to lines 130.

proximity_buttons is presently hosted at these locations:

https://bitbucket.org/kurtdekker/proximity_buttons

https://github.com/kurtdekker/proximity_buttons

https://gitlab.com/kurtdekker/proximity_buttons

https://sourceforge.net/projects/proximity-buttons/

I understood a little bit of the code. So I should get the transform of the camera and have it in update() so that it can run every frame, and then use that to calculate the rotation of the inputs?