August 11th, 2011 | Published in Google SketchUp, Uncategorized
Posted by Scott Lininger, SketchUp team
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.