- Home /
Using Mathf.Clamp in unity for boundries
I am making a 2D space shooter mobile game. I am trying to set a boundary so the ship does not go out of the screen. You can move the ship by tilting your phone. I have a shipController.cs attached to my ship object. And this is my FixedUpdate function:
public float xMin, xMax, yMin, yMax;
void FixedUpdate()
{
//tilt to move ship
transform.Translate(Input.acceleration.x * speed, Input.acceleration.y * speed, 0);
//create boundries
rigidbody2D.position = new Vector2(
Mathf.Clamp(rigidbody2D.position.x, xMin, xMax),
Mathf.Clamp(rigidbody2D.position.y, yMin, yMax)
);
}
The min and max values are defined in unity inspector. This code works great if you are testing on pc. But when exporting to the phone, the movement is very jittery and glitches. The ship will get to the boundary and kind of start jumping. The movement when tilting is also not very smooth. Is there any other way to make this smoother?
I wonder if this isn't an issue with the speed the ship is moving when it hits the bounds. Or rather, an issue with the amount of acceleration you're trying to put on it when it is at the boundary.
If you tilt the phone ever so slightly, does it still bounce?
yes. The more i tilt, the bigger the bounce. But if i tilt a little, it still bounces a little.
Answer by JonS · Oct 31, 2014 at 08:36 PM
Typically Physics objects don't like being moved around manually very much. FixedUpdate is for Physics stuff so if you want to use that you should be using rigidbody2D.AddForce() instead of Translate and position. Then you'd clamp the range and set the rigidbody's velocity to 0 if he was trying to move off the screen.
Alternatively, you can set the rigidbody to be Kinematic and move things in Update using what you have here if you don't really need the ship to be pushing things around with physics.
Answer by SheZii · Feb 07, 2019 at 08:44 AM
If you want to clamp/restrict gameobjects on the boundary of Minimap, here are the links
Youtube: https://www.youtube.com/watch?v=xW4zZQhRKlI
Step by step tutorial: http://techscenarios.com/unity3d-clamp-objects-on-edges-of-minimap-clamp-on-minimap-boundary-free-scripts-part-4/
Your answer
Follow this Question
Related Questions
Tilt an object when rotating and set it back to normal afterwards 0 Answers
How to get moving player to tilt when turning 0 Answers
Tilt Function. HELP! 1 Answer
gui and tilt function 1 Answer