There are many capabilities of the SketchUp Ruby API that aren't easy to discover. With over 1000 methods, it's not surprising! In this semi-regular blog series, I'll be pointing out my favorites.
Here's one: transforming individual vertices.
Let's say I've drawn a 2x2 grid of squares on the ground...
ents = Sketchup.active_model.entities
square1 = ents.add_face [0,0,0], [10,0,0], [10,10,0], [0,10,0]
square2 = ents.add_face [10,0,0], [20,0,0], [20,10,0], [10,10,0]
square3 = ents.add_face [0,10,0], [10,10,0], [10,20,0], [0,20,0]
square4 = ents.add_face [10,10,0], [20,10,0], [20,20,0], [10,20,0]
center_vertex = square1.vertices[3]
Easy. Now, this also gives me a 3x3 grid of vertices. Let's say I want to move that center_vertex 10" into the sky without moving the others. Can it be done?
If you go to the Vertex class documentation, there isn't a simple transform() method. There's a Vertex.position method... but alas, it's read only.
But wait! What about the parent class? A Vertex is an Entity, and so I can call any Entity method, too. Maybe there's a transform() method on the Entity class...
Nope.
At this point, you might have given up. (I know I did the first time I tried this...) But don't! The secret is that Entities.transform_entities can accept naked vertices as well as edges and faces. This wasn't obvious to me because if you iterate over the Entities collection, it doesn't contain vertices! So I just assumed that the transform_entities method wouldn't work on vertices. I was wrong, though. It'll accept any Entity, just like the documentation says. Check this out...
ents = Sketchup.active_model.entities
square1 = ents.add_face [0,0,0], [10,0,0], [10,10,0], [0,10,0]
square2 = ents.add_face [10,0,0], [20,0,0], [20,10,0], [10,10,0]
square3 = ents.add_face [0,10,0], [10,10,0], [10,20,0], [0,20,0]
square4 = ents.add_face [10,10,0], [20,10,0], [20,20,0], [10,20,0]
center_vertex = square1.vertices[3]
move_up = Geom::Transformation.new([0, 0, 10])
ents.transform_entities move_up, [center_vertex]
Hopefully that will help you out in some future plugin coding adventure.
What are your favorite "secrets" of the API? Share 'em in the comments.
1 comment:
Yea - I was stomped on this as well when I began to develop Vertex Tools.
One method which I found to be really useful was Entities.transform_by_vectors as it allowed me to transform multiple vertices with different transformation in one go - which speed up things a bit.
Though, that method doesn't take a transformation object, so I first need to iterate the vertices, transform their position and generate vectors from their original position to their new.
Post a Comment