Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more..
    Dismiss Notice
  3. Dismiss Notice

Mathf.Clamp issues...resctricting car movement

Discussion in 'Scripting' started by mridulbhagat120, Nov 27, 2018.

  1. mridulbhagat120

    mridulbhagat120

    Joined:
    Nov 8, 2018
    Posts:
    10
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class carController : MonoBehaviour {
    6.  
    7.     public float carSpeed;
    8.     public float maxPos = -633.3f;
    9.     Vector3 position;
    10.  
    11.     // Use this for initialization
    12.     void Start () {
    13.         position = transform.position;
    14.  
    15.        
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Update () {
    20.         position.x += Input.GetAxis("Horizontal") * carSpeed * Time.deltaTime;
    21.         position.x = Mathf.Clamp(position.x , -342.6f , -633.3f);
    22.  
    23.  
    24.  
    25.    
    26.  
    27.         transform.position = position;
    28.  
    29.        
    30.     }
    31. }
    32.  







    So what am i doing wrong here? The car shifts left entirely when i use this...I am no coder i just came up with it following tutorials. Its a script for restricting the car in frame when tapped.
    Thank you for any help!
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,357
    -633.3 is less then -342.6 so you need to switch them in this line of code:
    Mathf.Clamp(position.x , -342.6f , -633.3f);
     
  3. mridulbhagat120

    mridulbhagat120

    Joined:
    Nov 8, 2018
    Posts:
    10

    I tried that too...but with no help, even that gives erratic results!