3

I am trying to create bounce dynamics in a game that I'm programming on an arduino uno.
I can create a series of nested ifs but I've heard that a switch is faster.
I know that the case values are specified to be constants, but I'm curious if it's possible to make this code work?

// player and ball are both byte arrays
    switch(ball[0]) { // bounce off edges x-axis
        case (player[0]-1):
            ball[3] -= 2;
            break;
        case player[0]:
            ball[3] -= 1;
            break;
        case (player[0]+3):
            ball[3] += 1;
            break;
        case (player[0]+4): // At this line the compiler says: the value of 'player' is not usable in a constant expression
            ball[3] += 2;
            break;
    }

I'm pretty sure that the answer is either no, or that the workaround of putting the variables into constants will be much slower and larger than simply giving in to the nested ifs, but it doesn't hurt to ask.

Mikeologist
  • 438
  • 4
  • 11

1 Answers1

2

Avi Berger presented a fantastic solution which I was able to fit and to make work:

// player and ball are both byte arrays
    switch(ball[0] - player[0]) { // bounce off edges x-axis
    case 1:
        ball[3] -= 2;
        break;
    case 0:
        ball[3] -= 1;
        break;
    case -3:
        ball[3] += 1;
        break;
    case -4:
        ball[3] += 2;
        break;
    }
Mikeologist
  • 438
  • 4
  • 11
  • 1
    Are you sure your original code with if/else is a bottleneck? – Jabberwocky Mar 17 '20 at 07:50
  • @Jabberwocky No, I am not. My aim was to create a code snippet that responded in the same amount of time regardless of the option, that was fast, and that compiled small as it's for an MCU. I believe this now meets those intentions. – Mikeologist Mar 17 '20 at 12:48