Monday, December 28, 2015

Oblique Cylinder in OpenSCAD

While working in OpenSCAD I found the need to create an oblique cylinder, which is a combination between a rhombus and a cylinder. Unfortunately there is no easy way to create an oblique cylinder (at-least in version 2015.03-1) and by easy I mean something that can be done in three lines of code.

I ended up having to create a very trigonometry heavy module to accomplish this goal. Below is the code, which I hope saves some people a few hours. 

module ObliqueCylinder(height = 1, radius = 1, angle = 0, faces = 360) {
    theta = angle; 
    m = radius * sin(theta); 
    k = radius * sin(2 * theta);
    l = radius * pow(sin(theta), 2);
    hPrime = height/cos(theta) + 2 * m; 
    
    difference() {
        translate([0, -l, -1/2 * k]) {
            rotate(a = [-theta, 0, 0]) {
                linear_extrude(height = hPrime) {
                    rotate(a = [theta, 0, 0]) {
                        circle(r = radius, $fn = faces);
                    }
                }
            }
        }
        translate([0, 0, -1/2 * k]) {
            cube(size = [2 * radius, 2 * radius, k], center = true);
        }
        translate([0, height * tan(theta), height + k/2]) {
            cube(size = [2 * radius, 2 * radius, k], center = true);
        }
    }
}

Below is the result.

1 comment:

Robin said...


// It's only just over 3 lines... no trigonometry involved

module ObliqueCylinder2(ht = 1, rad = 1, angle = 0) {

difference() {

translate([0,0,-ht/2]) rotate(a = [-angle, 0, 0]) cylinder(h=ht*2,r=rad);
translate([0, 0, -ht]) cylinder(r=rad*20,h=ht); // make sure radius is big enough to cover a really skewed cylinder
translate([0, 0, ht]) cylinder(r=rad*20,h=ht);
}
}