简体   繁体   中英

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?

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. Same with the 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 . Calculate the direction (ie the angle) in the constructor, from the bullet position and the target position. velocity may also be a static constant, depending on your use case.

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.

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