Home > Blockchain >  Mathf.Clamp not working, does not restrict values
Mathf.Clamp not working, does not restrict values

Time:03-17

Im trying to restrict the movement (for now the z-axis) of my camera through the script attached to its pivot to the boundaries of a pool table and this is my script so far for testing.

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

public class cameraManager : MonoBehaviour
{

    void Start()
    {

    }

    void Update()
    {
        Vector3 cameraPos = transform.position;
        cameraPos.z = Mathf.Clamp(transform.position.z, -25, -4);

    }

} 

but what happens is that when I move the camera pivot using the movement keys through a script in another object; the camera pivot is not restricted and just goes beyond the set clamp. Did I miss something?

CodePudding user response:

Transform.position is a property with a getter and a setter and Vector3 a struct and therefore a value-type.

You only use the getter to return and store a local Vector3 but this is in no way aware or related to the transform.position anymore. It is a copied value.

Unless you assign something back to transform.position the setter is never called and thus whatever you do to the Vector3 the getter returned has no effect in your scene at all

void Update()
{
    Vector3 cameraPos = transform.position;
    cameraPos.z = Mathf.Clamp(cameraPos.z, -25, -4);
    transform.position = cameraPos;
}
  • Related