简体   繁体   中英

Libgdx + rotate sprite point to the touch position

I'm having problem trying to point my "arrow_sprite" to the touch position.

The result I want is that the arrow(the sprite that I want to rotate)will point to the touch position.

How can I acheive this?

You need to calculate the vector between the touch position and the sprite position. To do so you have to unproject the touch position received through your InputProcessor.

public class MyInputProcessor implements InputProcessor {
   ...

   @Override
   public boolean touchDown (int x, int y, int pointer, int button) {
      Vector3 touchDown = new Vector3(x, y, 0);
      camera.unproject(touchDown);
      Vector3 spritePosition = new Vector3(yourSpriteX, yourSpriteY, 0);
      spritePosition.sub(touchDown);
      return false;
   }

   ...
}

Now we have a vector pointing from your sprite to the touch position. From there you just need to calculate the rotation angle. One way would be to use Vector2.angle(), as such creating a Vector2 from the spritePosition Vector3.

If you want to draw in 2D, then you have to set your SpriteBatch to Camera.combined,

something like this : yourBatch.setProjectionMatrix(yourCamera.combined);

Then you must unproject the camera like "batch" said.

After, you must choose if you want to use a vector or 2d coordinate. Basically identycal ending for angle calculation :

First define a float degrees then make it like so in the touchDown method :

degrees = (float) ((Math.atan2 (touchPoint.x - arrowPosition.x, -(touchPoint.y - arrowPosition.y))*180.0d/Math.PI)+90.0f);

assuming you use a Vector3 or 2 for both input and arrow.

then when rendering the Arrow sprite :

Batch.draw(Arrow, x, y, originX, originY, width, height, scaleX, scaleY, degrees);

Hope this will be helpfull.

Just like Psilopat said, we define the degree by :

degrees = (float) ((Math.atan2 (touchPoint.x - arrowPosition.x, -(touchPoint.y - arrowPosition.y))*180.0d/Math.PI)+90.0f);

but if the rotation seems wrong, change the "+90.0f" at the end of line to something else. My arrow is pointing up, so I change it to "-180.0f"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM