Search code examples
ioscocos3d

need movement around z axis with coco3d


In my iOS app I have a 3D object created with cocos3d. It's moving correctly around x and y axes. But it does not want to move around z! Picture shows how it moves with the black arrows, and how it doesn't with red ones.

enter image description here

code from scene.m

-(void) touchEvent: (uint) touchType at: (CGPoint) touchPoint
{
    switch (touchType) {
        case kCCTouchBegan:
            break;
        case kCCTouchMoved:
            [self rotateMainNodeFromSwipeAt: touchPoint];
            break;
        case kCCTouchEnded:
            break;
        default:
            break;
}

// For all event types, remember where the touchpoint was, for subsequent events.
_lastTouchEventPoint = touchPoint;
}
#define kSwipeScale 0.6
-(void) rotateMainNodeFromSwipeAt: (CGPoint) touchPoint
{
    CC3Camera *camera = self.activeCamera;

    // Get the direction and length of the movement since the last touch move event,
    // in 2D screen coordinates. The 2D rotation axis is perpendicular to this movement.
    CGPoint swipe2d = ccpSub(touchPoint, _lastTouchEventPoint);
    CGPoint axis2d = ccpPerp(swipe2d);

    // Project the 2D axis into a 3D axis by mapping the 2D X & Y screen coords
    // to the camera's rightDirection and upDirection, respectively.
    CC3Vector axis = CC3VectorAdd(CC3VectorScaleUniform(camera.rightDirection, axis2d.x),
                              CC3VectorScaleUniform(camera.upDirection, axis2d.y));

    //CC3Vector axis = CC3VectorScaleUniform(camera.upDirection, axis2d.y);

    GLfloat angle = ccpLength(swipe2d) * kSwipeScale;

    // Rotate the node under direct finger control, by directly rotating by the angle
    // and axis determined by the swipe.
    [self.modelNode rotateByAngle:angle aroundAxis:axis];
}

Why it does not want to move around z axes?


Solution

  • Do you mean you want to rotate the node around the Z-axis of the camera? If so, the axis that you are deriving above (which is the same as code from CC3DemoMashUpScene), uses the camera's rightDirection and upDirection to create an axis that is perpendicular to the Z-axis of the camera, by definition. The rightDirection and upDirection define a plane that is perpendicular to the direction the camera is pointing, so any linear combination of these vectors will result in a vector that lies in that plane.

    To create rotation around the Z-axis, the axis must contain some Z component. The camera's forwardDirection can provide this Z-axis component. For the very simple example of rotating only around the camera's Z-axis, try setting the axis as:

    CC3Vector axis = CC3VectorScaleUniform(cam.forwardDirection, axis2d.x);
    

    or some combination of axis2d.x and axis2d.y.