Question

I'm trying to rotate an OpenGL object in iOS using touch, but I'm having some trouble. I am grabbing the user touches here:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
    UITouch *touch = [touches anyObject];
    startPoint = [touch locationInView:self.view];
    }

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
   {
   UITouch *touch = [touches anyObject];
   CGPoint point = [touch locationInView:self.view];
   dx = point.y - startPoint.y;
   dy = point.x - startPoint.x;
   startPoint = point;
   }

I'm using that in my update function to perform the rotation. Right now I'm just trying to rotate left to right when I touch left to right and then front to back when I go up and down. I get a weird combination rotation though. Here's the code:

- (void)update
   {    
   float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
   GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f);

   self.effect.transform.projectionMatrix = projectionMatrix;

   GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -3.5f);
   modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, -1, startPoint.x, startPoint.y, 0.0f);
   dx = dy =0;
   self.effect.transform.modelviewMatrix = modelViewMatrix;
   }
Was it helpful?

Solution

Because you're telling it to rotate in both x and y :)

Try this :

modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, startPoint.x, 1.0f, 0.0f, 0.0f);

This will rotate startPoint.x radians around the x-axis.

You can rotate about any axis you want by changing the last 3 parameters (i.e. 0,1,0 would rotate about the y-axis, 1,1,0 would rotate about a axis 45° between the x and y.)

NB Thanks @Marcelo Cantos for the clarification :)

OTHER TIPS

As per deanWombourne, you're using GLKMatrix4Rotate incorrectly. When you perform:

GLKMatrix4Rotate(modelViewMatrix, -1, startPoint.x, startPoint.y, 0.0f);

You rotate -1 radians around the axis (startPoint.x, startPoint.y, 0.0f). It sounds more like you want to rotate startPoint.x radians around (1, 0, 0) and startPoint.y radians around (0, 1, 0). So, for example:

modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, startPoint.x, 1.0f, 0.0f 0.0f);
modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, startPoint.y, 0.0f, 1.0f 0.0f);

Or you probably want to divide startPoint.x and startPoint.y, because that'll be hyper-responsive to touches.

It'll also have some gimbal lock issues — essentially because if you rotate around x first then the y axis isn't necessarily where you think it is, and if you rotate around y first then the x axis isn't necessarily where you think it is. Is that something you're concerned about?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top