我在试图将我的“arrow_sprite”指向触摸位置时遇到了问题。
我想要的结果是箭头(我想要旋转的精灵)指向触摸位置。
我该如何实现这个效果?
如果你想绘制2D图形,那么你需要将SpriteBatch设置为Camera.combined,就像这样:yourBatch.setProjectionMatrix(yourCamera.combined)。
接下来,你必须像"batch"所说的那样对相机进行反投影。
之后,你必须选择使用向量或2d坐标。角度计算的结束基本相同:
首先定义一个浮点数degrees,然后在touchDown方法中进行如下操作:
degrees = (float) ((Math.atan2 (touchPoint.x - arrowPosition.x, -(touchPoint.y - arrowPosition.y))*180.0d/Math.PI)+90.0f);
Batch.draw(Arrow, x, y, originX, originY, width, height, scaleX, scaleY, degrees);
希望这对你有所帮助。
您需要计算触摸位置和精灵位置之间的向量。为此,您必须通过输入处理器接收到的触摸位置进行反投影。
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;
}
...
}
现在我们有一个从你的精灵指向触摸位置的向量。从那里,你只需要计算旋转角度。一种方法是使用Vector2.angle(),因此从spritePosition Vector3创建一个Vector2。
degrees = (float) ((Math.atan2 (touchPoint.x - arrowPosition.x, -(touchPoint.y - arrowPosition.y))*180.0d/Math.PI)+90.0f);
但是如果旋转看起来不对,就将行末的“+90.0f”更改为其他值。我的箭头朝上,所以我把它改为“-180.0f”。