- Home /
I don't like Matf.clamp what to do ?
I am new to unity and after making some Wasd movement in unity 3d side I started doing a movement in unity 2d side and now after all moviy thing I want my object to be on boundary I tried on my own
if (this.transform.position.x < -11){
Console.WriteLine("You hit the boundary");}
but "your hit the boundary " never show off.instead it feels like this if function never gets triggered.but deep down i think i have to use matf.clamp for boundaries please help
Answer by Hellium · Aug 28, 2020 at 08:39 PM
You don't need to use it if you don't want to, basically, the implementation of Mathf.Clamp is
public static float Clamp(float value, float min, float max)
{
if(value < min) return min;
if(value > max) return max;
return value;
}
So you could have your own implementation if you want. Unity just provides you the function so you don't need to write it again.
One of the reasons the message never shows off is because you are using Console.WriteLine
instead of Debug.Log
Answer by mephistoII666 · Aug 28, 2020 at 09:03 PM
While you shouldn't reject a good solution out of prejudice, you don't really need to use mathf.clamp to setup worldspace movement limits.
In fact, ideally your movement would be limited by collider objects interacting with your player.
That's the best design philosophy: division of responsibilities. Your character moves itself around, but it's the wall who stops you from crossing it, not your character checking for walls on the way.
While I encourage you to keep experimenting with transform movement, you could be interested too in checking unity's official sample assets.
it has several sample character controllers, both 2D and 3D, built using the physics system: the characters move and collide against the physics colliders of the ground, walls and world.
Your answer
Follow this Question
Related Questions
Little problem with Mathf.Clamp as used in Space Shooter Tutorial 8 Answers
BoxCollider2d.bounds.Intersects Not Working 2 Answers
Clamping movement range on X-axis 0 Answers
Restricting movement with Mathf.Clamp 4 Answers
How to make UI slider decrease in increments by 0.1f as each bullet is shot. using currentBullets--; 1 Answer