Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
4
Question by mchechin · Mar 16, 2015 at 09:46 AM · c#scripting problemmathf.clamp

Restricting movement with Mathf.Clamp

Hi, I'm new to Unity and I'm trying to clone the Pong game right now but I'm stuck with movement restriction. I found one example that worked, but it worked in JS and I'm trying to learn C# so don't want to use any JS scripts now. The problem is that I want to restrict vertical movement of the paddle to -4.1f min and 4.1f max.

 using UnityEngine;
 using System.Collections;
 
 public class RacketController : MonoBehaviour {
     
     public float speed = 5.0f;
     
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         float yMove = Input.GetAxis("Vertical") * Time.deltaTime * speed;
         transform.Translate(0f ,yMove, 0f);
         transform.position.y = Mathf.Clamp(transform.position.y, -4.1f, 4.1f);
     }
 }

The similar code worked in JS but in C# the compiler returns an error on line where I try to clamp transform.position.y. I tried a lot of different solutions found on Unity Answers or in forums but I can't get it (or those examples won't work with my situation).

Comment
Add comment
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

4 Replies

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

Answer by asafsitner · Mar 16, 2015 at 09:52 AM

In C#, unlike UnityScript, the individual elements in a Transform's position property are not accessible directly.
Instead, you need to define a new vector and assign the whole of it, so for instance in your example you would do something like:

 void Update()
 {
     float yMove = Input.GetAxis("Vertical") * Time.deltaTime * speed;
     transform.Translate(0f, yMove, 0f);

     // initially, the temporary vector should equal the player's position
     Vector3 clampedPosition = transform.position;
     // Now we can manipulte it to clamp the y element
     clampedPosition.y = Mathf.Clamp(clampedPosition.y, -4.1f, 4.1f);
     // re-assigning the transform's position will clamp it
     transform.position = clampedPosition;
 }

Comment
Add comment · Show 4 · 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 mchechin · Mar 16, 2015 at 10:10 AM 0
Share

Thank you for such a detailed explanation! Now it's more clear to me :)

avatar image blainelight · Jul 08, 2018 at 03:01 PM 0
Share

Thank you Asaf! I was looking for hours to find this, and your code helped me to solve it. Really appreciate you posting!

Thanks again, Blaine

avatar image Wibiz · Mar 13, 2021 at 06:23 PM 1
Share

Holy moses man. Took me ages to find a viable code. Thank you ever so much!

avatar image john_goren · Aug 25, 2021 at 12:19 PM 0
Share

This is life-saving code. My advice to fellow newbs is to make sure at all time you are comparing apples to apples and oranges to oranges. I was stuck for a while because I was comparing Vectors of different kinds to each other (screen, viewPort, world...)

avatar image
14

Answer by Priyanshu · Mar 16, 2015 at 10:00 AM

In C# you cannot directly assign transform.position vector. As it is read only.

Change

 transform.position.y = Mathf.Clamp(transform.position.y, -4.1f, 4.1f);

to

 transform.position = new Vector3 (transform.position.x, Mathf.Clamp(transform.position.y, -4.1f, 4.1f), transform.position.z);




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 johnCpr · Jan 17, 2017 at 09:35 PM 0
Share

Thank you so much Priyanshu :3

avatar image
0

Answer by tarahugger · Feb 01, 2018 at 05:55 PM

Building upon Priyanshu's Answer, the following was what i needed to limit my top-down perspective camera movement for panning.

 void ClampTransform(Transform t, Vector3 origin, float distanceX, float distanceZ)
 {
     var z = Mathf.Clamp(t.position.z, origin.z - distanceZ, origin.z + distanceZ);
     var x = Mathf.Clamp(t.position.x, origin.x - distanceX, origin.x + distanceX);
     t.position = new Vector3(x, t.position.y, 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
avatar image
0

Answer by madhu_unity425 · May 18, 2019 at 06:49 AM

you can write Simple if condition also like this below

if(transform.position.y<=-4.1f) { transform.position = new Vector3( transform.position.x, -4.1f, transform.position.z); }

if(transform.position.y>=4.1f) { transform.position = new Vector3( transform.position.x, 4.1f, transform.position.z); }

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 Bunny83 · May 18, 2019 at 08:37 AM 0
Share

This is not really simpler nor easier to read nor better for performance. Each time you use transform.position you actually call a native code method which will return the whole vector3. Using a temporary variable as asafsitner did is easier to read and in most cases better for performance.

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

11 People are following this question.

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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How to create a game with numbers? 0 Answers

How do i set 60fps with RealSense(SR300, Color Camera, FaceTracking) 0 Answers

How can i rotate object by pressing on key R and keep object facing to me my self ? 0 Answers


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