I am trying to clamp the Rigidbody2D position between boundry.xMin and boundry.xMax and boundry.yMin boundry.yMax and assign that clamped value to the transform. This code allows the object to slowly drift out of the boundries I have set. I cannot figure what is wrong with this code. Can someone tell me what is wrong?
void Start()
{
rb = GetComponent<Rigidbody2D>();
// audioSource = GetComponent<AudioSource>();
}
void FixedUpdate ()
{
if (damage >= 100)
{
//Instantiate(explosion, transform.position, transform.rotation);
//gameController.GameOver();
}
float moveHorizontal = Input.GetAxis("Horizontal");
//float moveHorizontal = Input.acceleration.x;
if ((rb.position.x >= boundry.xMin) || (rb.position.x <= boundry.xMax))
{
Vector2 movement = new Vector2(moveHorizontal, 0);
rb.AddForce(movement * speed);
}
rb.position = new Vector3
(
Mathf.Clamp(rb.position.x, boundry.xMin, boundry.xMax),
Mathf.Clamp(rb.position.y, boundry.yMin, boundry.yMax),
-1f
);
Thanks