Learning and Applying Mathematics using Computing

Pixel Precision

Greenfoot stores the position of its actors as integer X-Y coordinates. This has the advantage of being simple for beginners to understand, and also makes certain aspects (e.g. drawing the actor’s image at the right place) straightforward. However, it also has a disadvantage.

Imagine that you want to move a small distance, 1 unit, at an angle of 30 degrees. Using trigonometry we can work out that we should move 0.87 units in the X direction, and 0.5 in the Y direction. However, since Greenfoot only tracks our position to the nearest pixel, we can’t move 0.87 pixels in X, we can either move 0 or 1. The obvious choice is to move 1 pixel in the X direction. Meanwhile, in the Y direction we can also move 0 or 1. If we move 0, then we’ve only moved in the X direction: that’s an angle of 0 degrees, not 30. But if we move 1, then we’ve moved 1 in both directions, which is an angle of 45 degrees not 30.

The way to solve this problem in Greenfoot is to make your actor store its X and Y coordinates in new floating-point variables, and adjust them when moving, but also tell Greenfoot the rounded version. That way, Greenfoot will still draw the actor in the nearest integer position, but small movements over time will end up being correct rather than incorrect as described above.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s