Potentials – Adding Arrows to Electric Field

Building Great Code

This morning I finished adding in the directional vectors to the display of the electric field on the Potentials app. Previously, we had the color indicate the magnitude of the field at each point, and then the contours were for lines of equal strength. But that's not really all that helpful for an electric field map - better, that each point have a little arrow indicating the direction of the field at that point. Then, you can see the shifting direction of the field, and where a test charge would feel force in the field.

The approach was to start with the points for line segments for the graphics primitives, and then modify them to suit the needs of each point. For example, assume an arrow, pointing to the right, lying on the x-axis, centered at the origin, and fitting with the unit square. There are five endpoints needed to draw these lines in one stroke, so lay them out. This is the starting point for all arrows.

Then we need to rotate it by the angle of the electric field at each point. This is in radians, and we can do this with the CGAffineTransform:

  CGAffineTransformMakeRotation(dir)

where dir is the angle of the field at that point.

Then we can scale the arrow for the size of the box in the view with:

  CGAffineTransformMakeScale(fac, fac)

because we want to look at the minimum size of the box, and call that fac.

Finally, we can move the arrow to the correct place in the view with:

  CGAffineTransformMakeTranslation(x+dx/2.0, y+dy/2.0)

And of course, we can use CGAffineTransformConcat to put these all together into one transformation that can then be applied to each point in the line segment:

  CGAffineTransform    xfrm = CGAffineTransformConcat(
                                CGAffineTransformConcat(
                                  CGAffineTransformMakeRotation(dir), 
                                  CGAffineTransformMakeScale(fac, fac)),
                                CGAffineTransformMakeTranslation(x+dx/2.0, y+dy/2.0));

because you can't call CGAffineTransformConcat with three arguments.

The results are just fantastic:

Electric Field Vectors

and it's easy to track where the test charge will feel the force of the field in every point in the workspace. This is just what we were hoping to get, and it wasn't all that hard with a standard arrow, and then a set of transformations.

Nice. 🙂