Your profile states you are on SketchUp 2022. Is this still true?
I ask be cause the 2023 release uses a different GUI framework that may have issues.
I cannot test you code, because you did not provide a test model with the definition and instances.
I suspect the weirdness is a result of your misuse of the selection object.
A quick look at your example code ā¦
(1) Ruby uses 2 space indentation.
(2) All the @@vars
in your class should be @vars
(ie, instance variables, as that is how you are using them.) In addition their initialization should be moved into an initialize
instance method which is called automatically by a classā new
constructor method after the object has been created. Any variables passed to new
are passed on to initialize
.
(3) You have the statement mod = Sketchup.active_model
, but then repeatedly call Sketchup.active_model
.
Likely, you should assign it to @model
in initialize
and use that instance variable throughout.
(4) Is a biggie. There is no need whatsoever to stuff objects into the selection set in order to iterate them. The Sketchup::ComponentDefinition#instances
method returns an Array
that has an #each
iterator (among others defined, as well as all those mixed in from module Enumerable
.)
(5) I would suggest you calculate what you can before the animation loop starts. Probably this means within the initialize
method. It is very inefficient to be getting the gear definitionās instances collection anew and reiterating it and recreating each instanceās rotational transformation again and again in every frame.
Ie, gears are pressed onto shafts and normally do not move. Their rotational transform will not change, ā¦ they will rotate by the same amount, about the same axis point, each frame.
(6) In the rp = Geom::Point3d.new(ent.bounds.center)
statement, it is frivolous to construct a point obejct. BoundingBox#center
already returns a Geom::Point3d
object.
(7) A toggle command usually reverses a Boolean variable:
def toggle_something
@something = !@something
end
Meaning, in Ruby it is kind of weird to use 0
and 1
for Boolean state.
I know this is a little test code, but we encourage proper coding here for a shared environment. (It seems like the various AI bots search the web for examples and think bad code are gospel because it posted on the web and parrot it as answers.)
(a) All code for SketchUp should be within a unique namespace module. It also is best to separate each of your extensions from others within the namespace using submodules.
(b) Local variables should not be created at the top level within the ObjectSpace.
(c) Only Ruby classes and select API classes should ever be defined in the top level ObjectSpace (because they become global.)
(d) Code that creates UI objects (commands, menu items, toolbars, buttons) should be wrapped within a load guard so that they are only created once.
See next post for an example ā¦