Cylinder texture mapping

I'm a bit of a novice with writing code and have been banging my head against this for hours. I'm simply attempting to map a texture to a cylinder and can not get this one bit of code right. It just maps the texture to one of the faces and stretches it out across all the rest.

Any help is greatly appreciated!

beginShape(TRIANGLE_STRIP);
texture(img);
for (int i = 0; i <= sides; i++) {
    float u = i/sides;
    float x = cos(i*angle)*r;
    float y = sin(i*angle)*r;
    vertex(x, halfHeight, y, u, 1);
    vertex(x, -halfHeight, y, u, 0);
  }
endShape(CLOSE);

Answers

  • I'm able to get it to work by changing textureMode() to IMAGE, but why doesn't it work when in NORMAL mode?

      beginShape(TRIANGLE_STRIP);
      textureMode(IMAGE);
      texture(img);
      for (int i = 0; i <= sides; i++) {
        float x = cos(i*angle)*r;
        float y = sin(i*angle)*r;
        float u = i*img.width/sides;
        vertex(x, y, halfHeight, u, 0);
        vertex(x, y, -halfHeight, u, 0.05*img.height);
      }
      endShape(CLOSE);
    
  • Answer ✓

    Integer division on line 4

  • Answer ✓

    float u = i/sides;

    When i and sides are both integers the result of the division will always be rounded to a full number. I guess "u" will always have a value of 0.0
    You can either turn one of the variables into a float or cast it for the division:

    float u = (float)i/sides;
    
  • edited December 2015

    ... the result of the division will always be rounded to a full number.

    Not exactly rounded. Rather the fractional part is removed from the result.
    It's equivalent to use (int) casting operator over the division's result.

Sign In or Register to comment.