简体   繁体   English

沿鼠标方向移动对象

[英]Move Object in direction of mouse

I have a bullet class and an algorithm that will move my bullet to where I pressed, but how would I have the bullet continuing on past the mouse_x and mouse_y when it was clicked? 我有一个项目符号类和一个将项目符号移动到按下位置的算法,但是当单击该项目符号时,如何使项目符号继续经过mouse_x和mouse_y?

In My Update method: 在“我的更新”方法中:

    float xSpeed = (MoveToX - x) / 9;
    float ySpeed = (MoveToY - y) / 9;

     this.x += xSpeed;
     this.y += ySpeed;

And this is when I first create the bullet: 这是我第一次创建项目符号时:

Bullet(int Mx, int My){
    c = Color.red;
    MoveToX = Mx;
    MoveToY = My;

    MoveToX += Board.cam.camX;
    MoveToY += Board.cam.camY;

Mx is the mouses x when it was clicked. Mx是单击鼠标X。 Same with the y. 与y相同。

Edit: This is my final product: everything works as it should 编辑:这是我的最终产品:一切正常

Bullet(int Mx, int My){
    c = Color.red;

    MoveToX = Mx + Board.cam.camX;
    MoveToY = My + Board.cam.camY;

    int speed = 5;
    float distance = (float) Math.sqrt(Math.pow(MoveToX - x, 2) + Math.pow(MoveToY - y, 2));


    amountToMoveX = (((MoveToX - x) / distance) * speed);
    amountToMoveY = (((MoveToY - y) / distance) * speed);

}


public void update(){

    x += amountToMoveX;
    y += amountToMoveY;

}

The instance variables of your bullet shouldn't be moveTo_ , but velocity and direction . 子弹的实例变量不应是moveTo_ ,而是velocitydirection Calculate the direction (ie the angle) in the constructor, from the bullet position and the target position. 根据项目符号位置和目标位置,计算构造函数中的direction (即角度)。 velocity may also be a static constant, depending on your use case. velocity也可能是静态常数,具体取决于您的用例。

If it is an option, I would strongly recommend to use a physics- or game-engine . 如果可以选择,我强烈建议您使用物理引擎或游戏引擎 Those kind of problems were already solved a hundred times in those engines. 这些问题已经在那些引擎中解决了一百次。 They relieve you from those basic tasks and help you concentrate on your actual problem. 它们使您摆脱了这些基本任务,并帮助您专注于实际问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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