Box2d + CoCos2d:自动移动对象以模拟游戏中的计算机移动

时间:2010-04-27 08:55:21

标签: cocos2d-iphone box2d

我正在打曲棍球比赛,我正在实施单人模式。我试图在进攻模式中移动“计算机”球拍(向球移动)。我正在使用CoCos2d和Box2d。我正在使用MouseJoints移动球拍。问题是Paddle根本没有移动!

在init方法中调用tick

[self schedule:@selector(tick:)];

...

  - (void)tick:(ccTime) dt 
 {
  _world->Step(dt, 10, 10);    

  CCSprite *computer_paddle;
  CCSprite *ball;
  b2Body *computer_paddle_b2Body;
  float32 direction;
  b2Vec2 velocity;


  for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {    
   if (b->GetUserData() != NULL) {
    CCSprite *sprite = (CCSprite *)b->GetUserData();      

    if (sprite.tag == 1) { //ball
     ball = sprite;
     static int maxSpeed = 10;
      velocity = b->GetLinearVelocity();
     float32 speed = velocity.Length();
      direction = velocity.y;

     if (speed > maxSpeed) {     
      b->SetLinearDamping(0.5);
     } else if (speed < maxSpeed) {
      b->SetLinearDamping(0.0);
     }

    } 

    if (sprite.tag == 3){ // paddle
     computer_paddle  = sprite;
     computer_paddle_b2Body = b; 


    }


  // update sprite position
  sprite.position = ccp(b->GetPosition().x * PTM_RATIO,b->GetPosition().y * PTM_RATIO);
  sprite.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()); 


  } 


 }


 // update the computer paddle in single player moving it towards the ball using MouseJoint


 //move towards the ball
 b2Vec2 b2Position = b2Vec2(ball.position.x/PTM_RATIO,ball.position.y/PTM_RATIO);

 b2MouseJointDef md1;


md1.bodyA = _groundBody;

md1.bodyB = computer_paddle_b2Body;

md1.target = b2Position;

md1.collideConnected = true;

md1.maxForce = 9999.0 * computer_paddle_b2Body->GetMass();

_mouseJoint = (b2MouseJoint *)_world->CreateJoint(&md1);

computer_paddle_b2Body->SetAwake(true);

1 个答案:

答案 0 :(得分:0)

检查是否:

a)身体正在睡觉

b)身体是一个静止的身体

如果它正在睡觉而您没有其他身体,请完全禁用睡眠。否则禁用身体睡眠:body-&gt; SetSleepingAllowed(NO)

注意:这是根据Box2D 2.2.1 API Reference而不是cocos2d 1.0中的默认值,因此Box2D版本的功能可能不同。

通过查找b2BodyDef的类型成员,检查您的身体是否是动态的,如有必要,将其设置为动态(请参阅b2BodyType枚举)。我不确定默认值是什么,它应该是动态的,但这可能取决于Box2D版本。

相关问题