2013-05-30 29 views
0

我需要讓Cocos2d照相機跟隨用戶在屏幕上觸摸的精靈(連接到Box2D身體)。當用戶拖動玩家時,我需要它能夠去世界的其他地方。這必須通過觸摸,而不是自動滾動。照相機跟隨着被觸摸的身體

我嘗試了幾種基於教程的方法,但似乎沒有解決這個問題。例如@Michael Fredrickson在這裏提供的解決方案Move CCCamera with the ccTouchesMoved method? (cocos2d,iphone)具有整個圖層的移動,但是當它移動時,屏幕上的精靈/身體具有無與倫比的座標,當我測試以查看它們是否被觸摸時,if(fixture->TestPoint(locationWorld))失敗。

我也看過這裏的教程http://www.learn-cocos2d.com/2012/12/ways-scrolling-cocos2d-explained/但這也不是我要找的。

任何幫助將不勝感激。

編輯:

我同意下方,因爲它讓我在正確的軌道上Liolik的答案。然而,最後一塊難題是,將從getPoint方法收到的值作爲實例變量,並從locationWorld中進行推導,我正在對TestPoint進行處理。就像這樣:

UITouch *myTouch = [touches anyObject]; 
CGPoint location = [myTouch locationInView:[myTouch view]];  
location = [[CCDirector sharedDirector] convertToGL:location]; 
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO); 
b2Vec2 diff = b2Vec2(difference.x, difference.y); 

for (b2Body* b = _world->GetBodyList(); b; b = b->GetNext()) { 
    b2Fixture* f = b->GetFixtureList(); 
    while(f != NULL) { 
     if(f->TestPoint(locationWorld-diff)) { 
      b2MouseJointDef def; 
      def.bodyA = _groundBody; 
      def.bodyB = b; 
      def.target = locationWorld-diff; 
      def.maxForce = 9999999.0f * b->GetMass(); 
      _mouseJoint = (b2MouseJoint*)_world->CreateJoint(&def); 
      b->SetAwake(true); 
     } 
    f = f->GetNext(); 
    } 
} 

回答

1
在更新功能

CGPoint direction = [self getPoint:myBody->GetPosition()]; 
[self setPosition:direction]; 


- (CGPoint)getPoint:(b2Vec2)vec 
{ 
    CGSize screen = [[CCDirector sharedDirector] winSize]; 

    float x = vec.x * PTM_RATIO; 
    float y = vec.y * PTM_RATIO; 

    x = MAX(x, screen.width/2); 
    y = MAX(y, screen.height/2); 

    float _x = area.width - (screen.width/2); 
    float _y = area.height - (screen.height/2); 

    x = MIN(x, _x); 
    y = MIN(y, _y); 

    CGPoint goodPoint = ccp(x,y); 

    CGPoint centerOfScreen = ccp(screen.width/2, screen.height/2); 
    CGPoint difference = ccpSub(centerOfScreen, goodPoint); 

    return difference; 
} 
+0

Liolik,getPoint方法中的「area」是什麼? – Eddy

+0

好的,我知道了,這個區域就是我的地圖的大小(我的情況是背景圖片)。所以現在我可以在拖動我的球員的同時四處移動,但過了一會兒,球員的身體就會鬆動,滾動停止。我知道我需要重新計算身體的位置以用新座標進行調整 - 但我不知道如何去做。 – Eddy

+0

我接受了答案,但請看看我的「編輯」在問題的身體看到最後一塊拼圖 - 爲我所需要的。 – Eddy

1

所以,如果我理解正確的,當精靈是屏幕中間的內部,背景是靜止的,而精靈跟隨你的手指,但是當您向邊緣滾動時,相機開始平移?

我在我的Star Digger遊戲中有一些大致相似的東西,其中有一艘船在屏幕中間,它自己的層必須在世界各地飛行,並且在船向主世界發射子彈時也遇到同樣的問題層。

繼承人我所做的:

float thresholdMinX = winSize*1/3; 
float thresholdMaxX = winSize*2/3; 

if(touch.x > thresholdMaxX) //scrolling right 
{ 
    self.x += touch.x - thresholdMaxX; 
} 
else if(touchX < thresholdMinX) 
{ 
    self.x += thresholdMinX - touchX; 
} 
else 
{ 
    sprite.position = touch; 
} 
CGPoint spritePointInWorld = ccp(sprite.x - self.x, sprite.y - self.y); 

然後每次計算碰撞的時候,你需要的,而不是重新計算精靈世界「實際」的位置,這是它的屏幕位置減去世界偏移,精靈屏幕的位置。

+0

謝謝,@redux。所以我想你對世界上每個精靈都做同樣的計算? – Eddy