Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by infiniteLoop · Jul 06, 2011 at 03:35 PM · mathfclamp

Mathf.Clamp() not working as expected.

I'm attempting to use the Mathf.Clamp() function to restrict the movement of a user controlled object. But for some reason, it doesn't seem to have any effect. All the examples that I have come across seem to be in Javascript, rather than my preffered C#, so I'm open to the possibility it could be a variable type issue of some sort. Can any of you kind folks see the issue?

 using UnityEngine;

using System.Collections;

public class MoveXY : MonoBehaviour {

 public Transform target;
 public float speedHorizontal = 10.0F;
 public float speedVertical = 10.0F;
 
 
 
 void Start () {
     
     if(!target)
         return;
     
     
 
 }
 

 void Update () {
 
     
     float translation = Input.GetAxis("Vertical") * speedVertical;
     translation = translation * Time.deltaTime;
     
     float translation2 = Input.GetAxis("Horizontal") * speedHorizontal;
     translation2 = translation2 * Time.deltaTime;
     
     
     
 
     
     
     target.transform.Translate(0.0F, translation, 0.0F);
     target.transform.Translate(Mathf.Clamp(translation2, -2.0F, 2.0F), 0.0F, 0.0F); 
     
     
 
     
     
     
 }
 
 
 
 

}

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Simon V · Jul 06, 2011 at 04:31 PM 0
Share

On a side-note, you can write things like translation = translation * Time.deltaTime as translation *= Time.deltaTime . It's the same with other operands.

avatar image infiniteLoop · Jul 07, 2011 at 11:25 AM 1
Share

Thanks for the response. I am actually familar with the short hand you mentioned, but I'm a little pedantic when it comes to writing this sort of expression lol - for some reason I tend to prefer the more verbose version.

4 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Bunny83 · Jul 06, 2011 at 04:07 PM

 public static Vector3 ClampVector3(Vector3 vec, Vector3 min, vector3 max)
 {
     return Vector3.Min(max,Vector3.Max(min,vec));
 }

This function will clamp a vector3 within the box defined by min and max. If you just want to clamp only one axis you have to do it that way:

 Vector3 pos = target.position;
 pos.x = Mathf.Clamp(pos.x, 2.0f, -2.0f);
 target.position = pos;
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image infiniteLoop · Jul 07, 2011 at 11:43 AM 0
Share

Wow, this is coding gold :D Thank you !

avatar image
3

Answer by sneftel · Jul 06, 2011 at 03:42 PM

I note that you're clamping the displacement of the object (its per-frame movement), not its absolute position. If you want to constrain its x position, translate it without clamping, then do target.transform.position.x = Mathf.Clamp(target.transform.position.x, -2, 2) afterwards.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunny83 · Jul 06, 2011 at 03:59 PM 4
Share

Just to mention it in C# you can't do it that way. position is a property and this line:

 target.transform.position.x = ...

Will call the getter of the position and return a copy of the Vector3 of which you are setting the x value. The actual position won't be affected.

You have to save a copy of the position and assign the Vector3 back to position.

avatar image infiniteLoop · Jul 07, 2011 at 11:38 AM 0
Share

Ah, so there is indeed a inherent C# issue located somewhere in this problem. I can only lament that most examples I come across are in Javascript for this very reason!

avatar image
3

Answer by Eric5h5 · Jul 06, 2011 at 03:42 PM

Mathf.Clamp always works as expected. Your code is limiting the speed. If you mean to limit the position, transform.Translate isn't what you want, since that's relative movement, not absolute.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image sona.viswam · Apr 16, 2013 at 06:14 AM 0
Share

This is my code moveDirection = Vector3.forward + new Vector3(Input.acceleration.x * 0.3f, 0, 0);

transform.Translate(moveDirection * Time.deltaTime *9);

transform.position.x = $$anonymous$$athf.Clamp(transform.position.x, -2.0f, 2.0f);

But i am getting error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable

avatar image Eric5h5 · Apr 16, 2013 at 06:24 AM 1
Share

You can only write code like that in Unityscript, not C#. As the error says, you should use a temporary variable; specifically a Vector3, then write it back.

avatar image Eric5h5 · Apr 16, 2013 at 06:49 AM 1
Share

No, the error is referring to transform.position. You can't write to transform.position.x in C#, you have to use a temporary Vector3 variable.

avatar image
0

Answer by AndyB_1992 · Sep 09, 2013 at 02:04 AM

I had a script which clamped x and y using transform.position to move my player - this worked fine. I tried to use the Translate method, and clamp the X and Y values in C# but did not work.
Annoying since using Translate() makes my object transform a lot smoother than using transform.position = new Vector(x,y,z) - this is too precise.

In order to use Translate() with clamps I had to write the code in Javascript (which worked) so that is one of your options. However I forgot I had a C# script that I found which results in smooth transformations that uses transform.position = new Vector 3 so here it is:

 using System.Collections;
 
 public class DragScript : MonoBehaviour
 {
 
     [SerializeField]
 
     float _horizontalLimit = 2.5f, _verticalLimit = 2.5f, dragSpeed = 0.01f;
     Transform cachedTransform;
     Vector3 startingPos;
 
     void Start ()
     {
         //Make reference to transform
         cachedTransform = transform;
         //Save starting position
         startingPos = cachedTransform.position;
     }
     
     void Update ()
     {
         if (Input.touchCount > 0) {
             Vector2 deltaPosition = Input.GetTouch (0).deltaPosition;
 
             //Switch through touch events
             switch (Input.GetTouch (0).phase) {
             case TouchPhase.Began:    
                 break;
             case TouchPhase.Moved:
                 DragObject (deltaPosition);
                 break;
             case TouchPhase.Ended:    
                 break;
             }
         }
 
     }
 
     void DragObject (Vector2 deltaPosition)
     {
         cachedTransform.position = new Vector3 (Mathf.Clamp ((deltaPosition.x * dragSpeed) + cachedTransform.position.x,
             startingPos.x - _horizontalLimit, startingPos.x + _horizontalLimit), 
 
         Mathf.Clamp ((deltaPosition.y * dragSpeed) + cachedTransform.position.y, startingPos.y - _verticalLimit, startingPos.y + _verticalLimit),
             cachedTransform.position.z);    
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Can someone explain this MouseMove script to me :) 1 Answer

A node in a childnode? 1 Answer

Mathf clamp movement to Camera space in js 0 Answers

Limiting player movement (Partially done) 1 Answer

How to scale an object between two values over distance 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges