Points being modified in for loop, not seeing why

I feel like there is an easy solution but all I want to do is connect the two sets of points. For some reason in the for loop the values of pts are different than outside the for loop.

I have tried cloning, duplicating, adding an extra points2=points then modifying that and nothing seems to work.

model = Sketchup.active_model
ents = model.entities
group = ents.add_group
# Problem
z = 1
point1=Geom::Point3d.new(0,0,z)
point2=Geom::Point3d.new(10,0,z)
point3=Geom::Point3d.new(10,10,z)
point4=Geom::Point3d.new(0,10,z)
point5=Geom::Point3d.new(0,0,z)

pts = [point1,point2,point3,point4,point5]

group.entities.add_edges pts

modified_pts = pts.each{|pt| pt[2] -=z}

group.entities.add_edges modified_pts

len = pts.length-1
for i in 0..len do
  group.entities.add_line pts[i],modified_pts[i]
end

This might be your problem.

The #each iterator always returns the receiver collection (in this case pts.)

What you really want is to create a copy of the array, so use Array#map, ie …

modified_pts = pts.map { |pt| pt.offset([0,0,-z]) }

Also, try to use the nifty #x, #y and #z (getter and setter) methods that the API adds to the core Array class, instead of indexes (unless in a loop, see below.)


Don’t do this …

len = pts.length-1
for i in 0..len do
  group.entities.add_line pts[i],modified_pts[i]
end

Instead do this …

pts.each_with_index do |pt,i|
  group.entities.add_line( pt, modified_pts[i] )
end

Or, if you want to get nifty and use Array#zip

group.entities.add_edges( pts.zip(modified_pts).flatten )

And since your not actually using the point1, point2, etc., references …

pts = [
  [0,0,z], [10,0,z], [10,10,z], [0,10,z], [0,0,z]
]
pts.map! { |ary| Geom::Point3d.new(ary) }

The bang method modifies the receiver collection object itself.

2 Likes