Search code examples
if-statementsmallbasic

if statements weird behavior


I was caught playing Slither during class. My punishment was to program the game in small basic.

I now have a row of balls and if the first ball rolls over the small dots. The dots will disappear and you will gain a point. The if statements that checks if the big ball is on the small dot is this:

If (foodX[x] - SnakeHeadX) < precision And (foodX[x] - SnakeHeadX) > -precision And (foodY[x] - SnakeHeadY) < precision And (foodY[x] - SnakeHeadY) > -precision Then

This if statement is in a for loop

For x = 1 To 500

So I get my points but when the big Ball his x value is and y value are smaller then 20 I also get points. Something that it is not meant to be.

This is the scenario ( The @ is the big ball )

---------------------------------------------------------------------------------------------
|@                                           *
|
|                           *
|                                                                       *
|  *                                  *
|
|                                          *
---------------------------------------------------------------------------------------------

As you can see the big ball does not touch small dots. But I do gain points. Why is it True then? And how do I fix it?


Solution

  • It sounds like you are trying to manage hit boxes. Where two shapes interact with each other. Also, your approach seems to be to calculate the distance between the two objects, and if it is below a thresh hold (your precision variable) you count it as a hit.

    I have two suggestions:

    1. Use the full distance formulate. You are currently checking X and Y separately and I image this is causing your problem
    2. Abandon distances in favor of hit boxes. This requires some very long and very complex If statements in Small Basic, but it gives you more control.

    Samples:

    'Distance from centers
    distance = Math.SquareRoot(Math.Power(foodX[x] - SnakeHeadX,2) + Math.Power(foodY[x] - SnakeHeadY),2)
    If distance < precision Then
      'feed the snake
    EndIf
    
    'Hit boxes
    If SnakeHeadX > foodX[x] And SnakeHeadX < foodX[x] And SnakeHeadY > foodY[x] And SnakeHeadY < foodY[x] Then 'top left corner of snake
      If 'top right coner of the snake
        ' Repeat for all four corners of the snake
      EndIf
    endif
    

    If this doesn't help clarify your problem. The more detail and the more sample code you provide the better.