# CoCo bouncing BASIC ball, part 2

See also: part 1, part 2, part 3, part 4 and part 5.

## Math is hard, but some is easier.

Since it seems we might be needing math to move the ball around, let’s revisit some benchmarks on math to see which is faster. Using my BENCH.BAS program:

```0 REM BENCH.BAS
5 DIM TE,TM,B,A,TT
10 FORA=0TO3:TIMER=0:TM=TIMER
20 FORB=0TO1000
70 NEXT
80 TE=TIMER-TM:PRINTA,TE
90 TT=TT+TE:NEXT:PRINTTT/A:END```

…let’s declare a temporary variable, and then see how fast it is to add different values.

```6 Z=0
30 Z=Z+1```

Changing that to hex 1 (Z=Z+&H1) is basically the same.

BUT, adding 1 would just be moving on byte to the right. If we were moving down and to the right, that would be adding 33.

Z=Z+33 produces 355. It’s having to do much more work to convert two decimal digits.

Changing that to Z=Z+&H21 results in 278. It seems adding two hex digits is faster than adding one decimal digit :-)

Obviously, any math we want to do should be done using hex. But what math do we need?

Let’s start with a simple example that tries to “bounce” a single character around the screen.

## Bounce this

As a kid, I would do this with an X and Y, which I would then convert to a screen position like this:

`PRINT@X+Y*32,"*";`

I would then use variables for “X Movement” (XM) and “Y Movement” (YM) and add them to X and Y each time:

```X=X+XM:IF X<1 OR X>30 THEN XM=-XM
Y=Y+YM:IF Y<1 OR Y>14 THEN YM=-YM```

There are problems with this approach (like, when it hits the bottom right of the screen, it scrolls up, and I’m also not erasing the “*”), but it’s good enough for a benchmark test:

```6 X=0:Y=0:XM=1:YM=1
30 PRINT@X+Y*32,"*";
31 X=X+XM:IFX<1ORX>30THENXM=-XM
32 Y=Y+YM:IFY<1ORY>14THENYM=-YM```

This produces 2047. If we change all the values to hex:

```6 X=0:Y=0:XM=1:YM=1
30 PRINT@X+Y*&H20,"*";
31 X=X+XM:IFX<&H1ORX>&H1E THENXM=-XM
32 Y=Y+YM:IFY<&H1ORY>&HE THENYM=-YM```

Note I had to add spaces after the &H1E and &HE since BASIC can’t tell that’s the end of a value before parsing the next keyword (“THEN”).

This one change improves the speed to 1842. A better way would be to eliminate the X and Y conversion completely, and just track one position (say, the top left corner). But without an X and Y, how do you know when you’ve hit the edge?

Since this is a demo, perhaps we don’t have to.

To be continued…

This site uses Akismet to reduce spam. Learn how your comment data is processed.