0

im using the below code but that doesnt seem to be stopping the sprite from going off screen even though the code builds. can anyone tell me how it needs to be changed so that when the sprite gets to the edge of the screen along the x coordinate it stops.

-(void)applyJoystick:(SneakyJoystick *)aJoystick toNode:(CCNode *)tempNode forTimeDelta:(float)deltaTime
{
CGPoint scaledVelocity = ccpMult(aJoystick.velocity, 1024.0f);
CGPoint newPosition = ccp(tempNode.position.x + scaledVelocity.x * deltaTime, tempNode.position.y);
CGSize screenSize = [CCDirector sharedDirector].winSize;
CGFloat spriteWidth = vikingSprite.contentSize.width;
CGFloat x = tempNode.position.x + scaledVelocity.x * deltaTime;
if (x < 0 + (spriteWidth/2)) {
    x = 0 + (spriteWidth/2);
} else if (x > screenSize.width - (spriteWidth/2)) {
    x = screenSize.width - (spriteWidth/2);

}
[tempNode setPosition:newPosition];
if (jumpButton.active == YES) {
    CCLOG(@"Jump button is pressed.");
}
if (attackButton.active == YES) {
    CCLOG(@"Attack button is pressed.");
}
}

thanks

4

3 回答 3

2

修改后的变量 x 永远不会重新分配给 vikingsprite。

因此,您需要执行以下操作:

if (x < 0 + (spriteWidth/2)) {
    x = 0 + (spriteWidth/2);
} else if (x > screenSize.width - (spriteWidth/2)) {
    x = screenSize.width - (spriteWidth/2);

}
CGPoint vikingPos = cpp(x, vikingsprite.position.y);
[vikingsprite setPosition:vikingPos];

我的语法可能是错误的我没有写很多objective-c,但我使用cocos2d-x,它是cocos2d的C++版本

于 2011-10-20T00:27:16.353 回答
0

我想你忘了重置它的位置?

if (x < 0 + (spriteWidth/2)) {
x = 0 + (spriteWidth/2);
tempNode.position.x = x;
} else if (x > screenSize.width - (spriteWidth/2)) {
x = screenSize.width - (spriteWidth/2);
    tempNode.position.x = x;


}
于 2011-08-26T15:37:58.500 回答
0

Set edge as boundary.

 boundary.SetAsEdge(b2Vec2(0,0), b2Vec2(winSize.width/PTM_RATIO, 0));

Don't forget to send Ray Wenderlich a beer.

于 2011-08-26T15:33:21.033 回答