0
votes

I am working on a game in cocos2d / box2d, and have everything working well, moving sprite, collisions, etc.

I want to add some elements that influence my moving sprite without the sprite touching or colliding with them, and have no idea how to do that.

My sprite can collide with objects, and I can do that no problem - but I am looking for an object that influences my sprite WITHOUT a collision - for example a fan that would blow wind that would push the sprite away, or a magnet type device that would attract my sprite to it.

If my sprite collides with such objects then it should register a collision and die, but if it just moves NEAR to the objects, then it should be attracted or repelled.

Any thoughts?

1
you can make sensor bodies which will generate contact events but no collision response, allowing you to apply a fixed impulse to any contacting body - LearnCocos2D
You can define area's and when your sprite body comes into that area you can change the gravity with respect to actions-FAN or MAGNET. - Renaissance

1 Answers

1
votes

You can apply forces (as in F = ma) to objects at any time to make them move.

Gravity in box2d is doing this all the time to make objects fall "down" if you have defined a gravity vector.

So, your fan doesn't have to be a real "object" in the sense that it has a body. You can apply the force from the fan at any time using the methods in box2d to the thing you want the fan to blow on. I have some code for an "EntityController" that applies thrust so it moves in a certain direction (target direction). This is the code for it:

   void ApplyThrust()
   {
      // Get the distance to the target.
      Vec2 toTarget = GetTargetPos() - GetBody()->GetWorldCenter();
      toTarget.Normalize();
      Vec2 desiredVel = GetMaxSpeed()*toTarget;
      Vec2 currentVel = GetBody()->GetLinearVelocity();
      Vec2 thrust = desiredVel - currentVel;
      GetBody()->ApplyForceToCenter(GetMaxLinearAcceleration()*thrust);
   }

In this case, the body is moving towards a target. But it could just as easily been the target is the direction the fan is blowing in and now the center of mass of the "thing being blown" is being pushed away from the fan.

All my objects have a maximum speed (GetMaximumSpeed(...)), so this function will only apply force until the object is moving at the max speed and then not apply any more (it is a natural feedback loop).

You are welcome to look at the rest of the code base here on git hub. It is also talked about in this post. Note that this is in cocos2d-x (C++), but the same c++ code will work in cocos2d if you declare the files as .mm (allows c++ code). Or just use the technique without the code as you see fit.

Was this helpful?