0
votes

My problem is when I move my sprite either directly upwards or directly sideways the sprite vibrates. I have tried some things but cant get it fixed. Here is my current code. The framework is libGDX. I have tried moving the sprite exactly to the mouse if its within 1 pixel range and other things but nothing works for me. Why does the sprite vibrate on a straight line and how can I stop it? Thanks!

float speed = 4; // the speed of the sprite

Vector3 mousePosition = new Vector3();

if (Gdx.input.isTouched()) 
{

  camera.unproject(mousePosition.set(Gdx.input.getX(), Gdx.input.getY(), 0));

  if(mousePosition.x > 0 && mousePosition.x < Screen.WIDTH )
  { 

    if(mousePosition.y > 0 && mousePosition.y < Screen.HEIGHT)
    {


      if(mousePosition.x > player.x + (player.width /3))
      {
         player.x+=speed;
      }

     else if(mousePosition.x  < player.x + (player.width /3))
     {
        player.x -=speed;
     }

     if(mousePosition.y  > player.y + (player.height /2))
    {
       player.y+=speed;
    }

    else if(mousePosition.y < player.y + (player.height /2))
   {
      player.y-=speed;
   }



  }
}



}
batch.draw(player.sprite, player.x, player.y);
1

1 Answers

0
votes

Consider the case where you are moving the player vertically up. In this case mousePosition.x remains constant and mousePosition.y increases. mousePosition.y increases in such a way that player.y never exceeds it, and so the sprite follows the mousePosition in the Y direction. But remember that mousePosition.x remains constant. So according to your code player.x will increase till it satisfies the condition mousePosition.x > player.x + (player.width /3), and once it exceeds that value, player.x will start decreasing till it satisfies mousePosition.x < player.x + (player.width /3). That means player.x is increasing and decreasing, causing it to vibrate in X direction. Same case occurs when you move horizontally. But in this case, the sprite will vibrate it Y direction