lwjgl / java在移动时沿鼠标方向拍摄

时间:2014-12-22 19:01:52

标签: java opengl lwjgl

当我在该位置射击时,角色从子弹开始向右方向移动。但是如果我移动到不同的位置,子弹就不会朝着正确的方向前进。 为了澄清事情,mx是鼠标x位置,我是鼠标y位置,px是玩家x位置,py是玩家y位置。

package Player;

import java.io.IOException;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

import Game.Main;

public class Bullet {
public double x = 0, y = 0;
public double sx, sy;
public Texture texture;

public Bullet(double mx, double my, double px, double py){
    sx = mx-px;
    sy = py-my;
    x = px;
    y = py;
    sx = sx/Math.sqrt((mx-x)*(mx-x) + (my-y)*(my-y));
    sy = sy/Math.sqrt((mx-x)*(mx-x) + (my-y)*(my-y));



}
public void logic(){
    renderBullet();

     x+=sx * 8;
     y+=sy * 8;






}

public void renderBullet(){
    try {
        texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/image.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Color.white.bind();
    texture.bind(); // or GL11.glBind(texture.getTextureID());
       GL11.glBegin(GL11.GL_QUADS); 

       GL11.glTexCoord2f(0,0);
        GL11.glVertex2d(x,y);
        GL11.glTexCoord2f(1,0);
        GL11.glVertex2d(10+x,y);
        GL11.glTexCoord2f(1,1);
        GL11.glVertex2d(10+x,10+y);
        GL11.glTexCoord2f(0,1);
        GL11.glVertex2d(x,10+y);

    GL11.glEnd();
}

}

1 个答案:

答案 0 :(得分:0)

出于某种原因,在开始时处于不同位置时,您必须将sx和sy方程乘以-1。

public Bullet(double mx, double my, double px, double py){
    if(x==640 && y== 320){
    sx = mx-px;
    sy = py-my;
    x = px;
    y = py;
    sx = sx/Math.sqrt((mx-x)*(mx-x) + (my-y)*(my-y));
    sy = sy/Math.sqrt((mx-x)*(mx-x) + (my-y)*(my-y));

}
    if(x!=640 && y!= 320){
    sx = px-mx;
    sy = my-py;
    x = px;
    y = py;
    sx = sx/Math.sqrt((mx-x)*(mx-x) + (my-y)*(my-y));
    sy = sy/Math.sqrt((mx-x)*(mx-x) + (my-y)*(my-y));

}

}