快速連結

2014年3月11日

【Cocos2D 3.x】 PhysicBody使用方式

範例是參考官方網站上的 Color Matching game
CCNode內有一個新的屬性為physicsBody,為的是建立起Node的Physic運算,必須使用CCPhysicsBody來宣告其物件,並且設定。
但是單單CCPhysicsBody並無法成事。

好啦說了那麼多,直接看程式碼比較快囉!



Ball.m

-(id)init{
    if ((self = [super initWithImageNamed:@"ball.png"])){
        
                // Estimate the ball's radius using half of the sprite's width.
  CGFloat padding = 5;
  CGFloat radius = 0.5*(self.contentSize.width - padding);
  
  // 我給這個物件為圓形,所以讓他有邊角。
  CCPhysicsBody *body = [CCPhysicsBody bodyWithCircleOfRadius:radius andCenter:self.anchorPointInPoints];//self.anchorPointInPoints
  
                //通常這數值是1.0,也不用怎麼改了,除非要改重一點。
  body.density = 1.0;
  
  // 摩擦值,通常給0.7。
  body.friction = 0.7;
        
                //速度的意思,基本上設置看狀況。
                body.velocity = ccp(1.0, 0);
                //角速度,也就是物體在轉動的時候的速度。
                body.angularVelocity = 1.0;
        
  // 當使用collision delegate時候,要知道是碰到哪個物件了,所以賦予其名稱。
  body.collisionType = @"ball";
  
  // 設定屬性完成後就設給這顆球吧!
                self.physicsBody = body;
        
    }
    return self;
}



然而僅僅這樣仍然無法讓球成為一個可以物理運動的物體。
必須賦予它一個環境。

MainScene.m


@implementation GameScene{
    CCSprite *background;
    
    Ball *ball;
    
    // Node that simulates the physics.
    CCPhysicsNode *_physics;
 
    // The boundaries of the "bin" that the balls are trapped inside of.
    CGRect _binRect;
}

-(void)onEnter
{
    [super onEnter];
    
    background = [CCSprite spriteWithImageNamed:@"background.jpg"];
    [self addChild:background z:Z_BACKGROUND];

    
    // Create the physics node to simulate the physics in.
    _physics = [CCPhysicsNode node];
    _physics.gravity = ccp(0, -100); //-250
    [self addChild:_physics z:Z_BALL];
 
    // Use the scene itself as the delegate for collision events.
    // See the collision methods below.
    _physics.collisionDelegate = self;
    [_physics setUserInteractionEnabled:YES];

    
    // 設置一個墜落範圍,內容為空,而且不會移動。
    CCNode *bin = [CCNode node];
    _binRect = CGRectMake(20, 20, 600, 920);
    bin.physicsBody = [CCPhysicsBody bodyWithPolylineFromRect:_binRect cornerRadius:0];


    [_physics addChild:bin];

    // 加入ball物件
    ball = [Ball node];
    ball.position = ccp(self.contentSize.width/2,self.contentSize.height/2);
    [_physics addChild:ball];
    
}




這樣子就可以讓球滾來滾去囉。

沒有留言:

張貼留言

歡迎大家留言提問,我會答的都會盡力回答!
如果太久沒出現回應就是我又忘記回來看留言了TAT