开发者

Apply Linear Impulse to Rotation of Sprite- Cocos2d/Box2D

开发者 https://www.devze.com 2023-04-03 03:15 出处:网络
I have an arrow and a ball. The anchorPoint for the arrow is on the bottom. All I need to do is have the sprite be able to rotate with touch, then a linear impulse is applied to the ball and shot in t

I have an arrow and a ball. The anchorPoint for the arrow is on the bottom. All I need to do is have the sprite be able to rotate with touch, then a linear impulse is applied to the ball and shot in the direction the a开发者_运维百科rrow is pointing to.

E.G.

Say you rotate the arrow 70 degrees then press the fire button. The ball is then shot in a 70 degree angle.

Currently, this is what I am using but the ball does not shoot in the direction the arrow is pointing too.

Rotates arrow with touch.

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];

    //acquire the previous touch location
    CGPoint firstLocation = [touch previousLocationInView:[touch view]];
    CGPoint location = [touch locationInView:[touch view]];

    //preform all the same basic rig on both the current touch and previous touch
    CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
    CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];

    CGPoint firstVector = ccpSub(firstTouchingPoint, _arrow.position);
    CGFloat firstRotateAngle = -ccpToAngle(firstVector);
    CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);

    CGPoint vector = ccpSub(touchingPoint, _arrow.position);
    CGFloat rotateAngle = -ccpToAngle(vector);
    CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);

    //keep adding the difference of the two angles to the dial rotation
    arrowRotation += currentTouch - previousTouch;
}

Fire Button to shoot the ball in the direction the arrow is pointing too.

-(void) fireBall: (id)sender
{
    [self unscheduleUpdate];

    direction = arrowRotation;
    b2Vec2 force = b2Vec2(direction, 24.8);
    _ballBody->ApplyLinearImpulse(force, _ballBody->GetWorldCenter());
}

Any help is greatly appreciated! Thanks in advance!


The impulse you are applying to the ball is (direction, 24.8). Should it not be: (direction.x * 24.8, direction.y * 24.8). This may not be the only problem, but it's one that jumped out at me.

0

精彩评论

暂无评论...
验证码 换一张
取 消