Rotate Texture in function of player position

China☆狼群 提交于 2019-12-02 14:43:14

问题


I'm making a 2d game that consists in a plane fighting against spaceships trough missiles, i want the spaceships to rotate in function of the player position, so that they are always facing the player with the "head". The player can move freely in the y and x directions. THe player and the spaceships have a Vector2 pos variable, that corresponds to their actual position. Any help would be appreciated.

This is my (now working) code:

    public void render(SpriteBatch sb) {     Vector2 temp = new Vector2();     float angle = temp.set(entityManager.getPlayer().pos).sub(pos).angle();     TextureRegion region = new TextureRegion(texture);     sb.draw(region, pos.x, pos.y, 0, 0, texture.getWidth(), texture.getHeight(), 1.0f, 1.0f,angle+90); } 

The enemy spaceships rotate, but they dont always face the player:


回答1:


The @dwn's answer is mathematically correct, but when you deal with LibGDX framework it's better to use native tools.

If you have positions of enemy and player storing in Vector2s then you may perform computations a bit convenient. For example, to determine angle between specific enemy and player:

Vector2 enemyPos; Vector2 playerPos; Vector2 temp;  float angle = temp                 .set(playerPos)                 .sub(enemyPos)                 .angle(); 

This will give you exactly what you want. Of course it's better to keep temp vector in somewhere in public space to use it in such numerous calculations. You better to check other convenient Vector2methods, it will seriously easy your life.

Good luck.




回答2:


I think this should work. Set..

v = centerPosOfShip - centerPosOfUFO 

Normalize...

v /= sqrt( v.x * v.x + v.y * v.y ) 

So now we can say v = [ cos(theta) sin(theta) ]; the rotation matrix is...

[ cos(theta)  -sin(theta) ] [ sin(theta)   cos(theta) ] 

So we can write in terms of v-components...

[ v.x  -v.y    centerPosOfUFO.x ][x] [ v.y   v.x    centerPosOfUFO.y ][y] [ 0     0      1                ][1] 

where [x y] is any point on the UFO relative to its center.

Hope that makes sense



来源:https://stackoverflow.com/questions/27671908/rotate-texture-in-function-of-player-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!