- Home /
Restricting Position Between Two Points
Hi, I am making a game in which the red cube has to move between two borders (blue ones). I have a script to move it, but it should not go through borders. Check the screenshot.
Thanks you in advance
Answer by Duckocide · Oct 26, 2020 at 09:46 PM
There are a couple ways to restrict the cube.
1) If the blue items are static you can use Mathf.Clamp(...) function on the x-axis value of the cube. I.e. The red cube x-axis value is clamp between a low value (right cube inner edge) and high value (left cube inner edge).
or
2) You can use physics and colliders (a box collider on the two borders scaled to their size) and a box collider and dynamic (Kinematic tick off) rigidBody component added to the cube. You'll need to switch off gravity on the red cube rigidBody as well.
Moving objects around in physics is different to just adding values to the transform x,y,z values of the cube. You'll need to apply forces and think about both angular and direction velocity drag (to slow the cube over time). You can lock things like angular velocity if you don't want the cube to spin.
Have a look at https://learn.unity.com/tutorial/physics-challenges#5c7f8528edbc2a002053b527 - It's a good primer for the simpler side of physics in Unity.
Thanks a lot, it helped me a lot. These are what I have done: 1. I assigned rigidbody.angularVelocity to Vector3.zero. 2. Then I changed the red cube's mass, direction drag, and speed value (Which I declared in order to change speed of object). So, I have got smoother movement. 3. Also, I freezed position on y and z axis, so it is not going to move in those axis.
And, I got what I want
Your answer
![](https://koobas.hobune.stream/wayback/20220613014610im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Making a bubble level (not a game but work tool) 1 Answer
z-axis movement 1 Answer
How to rotate and move a cube (Like This) 1 Answer
Jet-Pack Script 1 Answer