Hello everyone! I'm trying to create a limit for my player. The player is moved with accelerometer but when i'm trying to use mathf.clamp it's not work =(, this is my code: Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Aeroplano : MonoBehaviour { // Use this for initialization [SerializeField] private float LimiteSx; [SerializeField] private float LimiteDx; private float Speed = 40f; void Start () { } // Update is called once per frame void Update () { transform.Translate(Input.acceleration.x * Time.deltaTime * Speed, 0, 0); /*transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y, -2.82f, 2.82f), transform.position.z); Vector3 ClampedPosition = transform.position; ClampedPosition.y= Mathf.Clamp(transform.position.x, -2.82f, 2.82f); transform.position = ClampedPosition; */ } }
In your commented code you've used "transform.position.x" but I think you meant "transform.position.y".
Why? My player move only on the x axis so the y is 0... so I modified the code but don't work... Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Aeroplano : MonoBehaviour { // Use this for initialization [SerializeField] private float LimiteSx; [SerializeField] private float LimiteDx; private float Speed = 40f; void Start () { } // Update is called once per frame void Update () { transform.Translate(Input.acceleration.x * Time.deltaTime * Speed, 0, 0); //transform.position = new Vector3(Mathf.Clamp(transform.position.x,-2.82f, 2.82f), transform.position.y, transform.position.z); Vector3 ClampedPosition = transform.position; ClampedPosition.x= Mathf.Clamp(transform.position.x, -2.82f, 2.82f); transform.position = ClampedPosition; } }
Code (CSharp): ClampedPosition.y = Mathf.Clamp(transform.position.x, -2.82f, 2.82f); In this line in your first example you were setting the Y position by clamping the X position. You never actually explained how your game works so I had no idea what you were trying to do, I was just pointing out a logical error. What is supposed to be happening? Your player only moves on the X axis? Which value are you trying to clamp?
yeah sorry , so my character is moving on the x axis and i try to clamp two x values for limit the moving of my character
What you have there should be properly clamping the X position. Are you seeing it not clamp on the X, or are you seeing movement on the Y?
Nope, I'm not seeing movement on the y but on the x axis the character move free =( (the clamp create a range on the x axis where the character move in, so it don't work)
I dont understand, in your script you aren't applying any offset to the Y, and you are in fact clamping the X. Is this script actually being applied to the object? Try printing out position with Debug.Log to make sure it's actually running that code.