Coding Left and Right walls

Vector3 xLimit = new Vector3(Mathf.Clamp(this.transform.position.x,0.5f,15.7f),
Mathf.Clamp (this.transform.position.y,0.5f,15.5f),
this.transform.position = xLimit;

this code works as in it limits the ball from going outside the left and right bounds but it doesn’t make it so that the ball bounces back, as you have shown in the video using colliders, was wondering what is wrong with this code or is just simply not possible with code.

Thanks for all the help!


I would suggest that you use box colliders to restrict the ball.

I am new to Unity, but have been a developer for 20+ years. In any software language, there is "more than one way to skin a cat."
By relying on the Physics2D engine and employing box colliders, Unity takes care of all the math for you. HOWEVER, if you want to do your own math (and honestly, not a bad idea to thoroughly understand what the physics engine is actually doing), you can define your limits as shown above, but then you need to use RayCast2D and determine your normal vectors at point of impact.
TLl;DR: box colliders are way, WAY easier to handle bounces and reflections.

Yes, just wanted to know how it worked, logic and so on. But i guess just knowing how to use colliders for now is good enough. I’ll look into it on unity’s website :slight_smile: Thank you for the response both of you!!

Privacy & Terms