# How to loop function when contact in Box2d

**URL:** <https://discourse.processing.org/t/how-to-loop-function-when-contact-in-box2d/22832>\
**Category:** Libraries\
**Created:** [July 25, 2020, 4:04pm UTC](https://discourse.processing.org/t/how-to-loop-function-when-contact-in-box2d/22832 "2020-07-25T16:04:10Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![weijie](https://avatars.discourse-cdn.com/v4/letter/w/9dc877/32.png) [@weijie](https://discourse.processing.org/u/weijie)\
**Post date:** [July 25, 2020, 4:04pm UTC](https://discourse.processing.org/t/how-to-loop-function-when-contact-in-box2d/22832/1 "2020-07-25T16:04:10Z")

</div>

I am trying to create a program so that the robots and the box will attract to each other when they are in contact (figure below)

I want them to keep being attracted when they are in contact  
But my problem now is the code in `beginContact()` just ran once when they are in contact (code attached below)

May I know how can I solve this?  
Thanks!

![IMG_2171](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/e/e9849a60e2db30976bc6a67bf3ec7d7c4740b108.jpeg)

```auto
void beginContact(Contact cp) {

    //…code to get fixtures, body, and object…

    if (o1 == null || o2 == null)
      return;

    //collision of robot and box
    if (o1.getClass() == Box.class) { //o1 is box
      if (o2.getClass() == Robot.class) { //o2 is robot
        Robot r = (Robot) o2;
        r.change();

// I want these 3 rows to keep running as long as there’s contact made
        Vec2 force = box.attract(r);
        box.applyForce(force);	//applying force to box
        r.applyForce(force.mul(-1));	//applying force to robot(resultant force)
      }
    } 

```
