clear3d()
removes all objects, as you've discovered. To remove a single object, you want rgl.pop()
.
As long as you know a given shape's object ID (i.e. its position on the stack of plotted objects), you can use rgl.pop()
to remove it. The key bookkeeping detail, then, is that you must keep track of the object ID of any object you may later want to remove.
(Conveniently, most rgl functions whose side-effect is to draw an object to the rgl device return the object ID (or vector of IDs) as their return value. Alternatively, use rgl.ids()
to access the object IDs of all objects plotted on the current device.)
A few more details from ?rgl.pop
:
RGL holds two stacks. One is for shapes and the other is for lights. 'clear3d' and 'rgl.clear' clear the specified stack, or restore the defaults for the bounding box (not visible) or viewpoint. By default with 'id=0' 'rgl.pop' removes the top-most (last added) node on the shape stack. The 'id' argument may be used to specify arbitrary item(s) to remove from the specified stack.
So in your case you might do:
library(rgl)
ii <- shade3d(translate3d(cube3d(), 1, 1, 1), col="blue", alpha = 1)
shade3d(translate3d(cube3d(), 1, 1, 1), col="white", alpha = 0.5)
rgl.pop(id = ii)