0

I am making a game where the character speeds up in the direction of the mouse when it is press. Along the +x +y to -x -y axis it works, but along the +x -y to -x +y axis it behaves erratically and then crashes with a floating point exception, like this gif:enter image description here shows. I am using raylib, here is my code:

        Vector2 goToPosition = GetMousePosition();
    if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) {
      Vector2 relative = {goToPosition.x - ballPosition.x, goToPosition.y - ballPosition.y};
      if (abs(relative.x) > abs(relative.y)) {
            velocity.x += relative.x > 0 ? 5 : -5;
        velocity.y += relative.y > 0 ? 5 * (abs(relative.x) / abs(relative.y)) : 5 * -(abs(relative.x) / abs(relative.y));
      }
      else if (abs(relative.x) < abs(relative.y)) {
        velocity.x += relative.x > 0 ? 5 * (abs(relative.y) / abs(relative.x)) : 5 * -(abs(relative.y) / abs(relative.x));
        velocity.y += relative.y > 0 ? 5 : -5;
      }
      else if (abs(relative.x) > 0) {
        velocity.x += relative.x > 0 ? 5 : -5;
        velocity.y += relative.y > 0 ? 5 : -5;
      }
  
      printf("%f, %f \n", velocity.x, velocity.y);
    }
    
        velocity.x = Lerp(velocity.x, 0, 0.1);
    velocity.y = Lerp(velocity.y, 0, 0.1);
    
    velocity.x = Clamp(velocity.x, -50, 50);
        velocity.y = Clamp(velocity.y, -50, 50);
    
    ballPosition.x += velocity.x;
    ballPosition.y += velocity.y;
ARI FISHER
  • 343
  • 1
  • 13
  • Watch out for 'divide by zero' in your expressions. – Weather Vane Mar 20 '21 at 12:12
  • Avoiding that seems to help a lot. – ARI FISHER Mar 20 '21 at 12:15
  • If `Lerp()` takes floating point values is that what you are working with? If so, note that `abs()` is for integer types (you don't show), otherwise use `fabs()` or `fabsf()`. – Weather Vane Mar 20 '21 at 12:16
  • ahhh, that should also help. I am working with floats – ARI FISHER Mar 20 '21 at 12:18
  • Hm. Your formulas look a bit off. I'm not sure why you distinguish the cases, which are about different slopes. And you don't really need the ternary comparisons if the result differs only in sign: `(y > 0) ? abs(x) / abs(y) : -abs(x) / abs(y)` is the same as `abs(x) / y`. (Both will cause trouble when `y == 0`.) You also add to the current velocity, so all your right-hand sides are effectively accelerations. (But perhaps that is by design.) – M Oehm Mar 20 '21 at 12:22
  • 1
    I mean, it looks as if you should just normalize your relative vector (again a possibility for divisions by zero!) and multiply it by 5. – M Oehm Mar 20 '21 at 12:27
  • @MOehm thanks, I just looked it up and raylib has a built in method (in raymath) for that that works better than my broken implementation. – ARI FISHER Mar 20 '21 at 12:37

0 Answers0