Stop moving when colliding. 2D

Hello everyone, hope you’re doing awesome!

So, I’ll make this quick.

Im moving a sprite using this script.

moveSprite.cs (Attached to moving object).

if(buttonIsPushed)
{

			
			transform.Translate (Vector3.left * speed * Time.deltaTime);

			//Clamping user from movign outside map bounds.
			tempPosition = transform.position;
			tempPosition.y = Mathf.Clamp(tempPosition.y, minY, maxY);
			tempPosition.x = Mathf.Clamp(tempPosition.x, minX, maxX);
			transform.position = tempPosition;

			
			//Button false
			gui.leftClicked = false;
			
}

Quick scan.

1.Transform moves sprite,
2.Map clamp so user doesn’t go outside map bounds.

Now I want to restrict the sprite from moving if he’s colliding with another gameObject.

How could I achieve this?

Thanks for your tips & help!

Have an awesome day!

:smiley:

You can use OnCollisionEnter2D() and OnCollisionExit2D() to set a flag line ‘isColliding’. Then change line 1 to:

if (buttonIsPushed && !isColliding)

Alternately, if your sprite is a square or a circle (or you can live with a square or circle detection), you can use Physics.OverlapCircle() or Physics.OverlapArea() to detect if your object is colliding.