Allegro和C ++ - 鼠标位置逻辑难度大

时间:2014-10-15 13:17:33

标签: c++ logic mouse allegro

我正在制作一个简单的游戏,它意味着使用计算机的鼠标来控制其中的物体,而且我很难让它像我一样运作喜欢。对象(在这种情况下标记为'拳击')意味着跟随鼠标在屏幕上的位置,直到达到某个常数('到达'),然后它将继续跟随鼠标,但只有在最大范围的范围内。基本上这个家伙的手跟着你的鼠标到了一个点,但是如果你的鼠标走得太远,他就不会从他的肩膀上扯下来。到目前为止我对该函数的代码是:

void FistPosition(int& player_x,int& player_y, int& fist_x, int& fist_y){ //Start
ALLEGRO_MOUSE_STATE mousepos;
al_get_mouse_state(&mousepos); //Get the mouse's x and y position

const int REACH = 150; //Define the maximum distance the fist can go.

int playerc_x = player_x + 62; //Define the x and y center of the player object
int playerc_y = player_y + 92;

double x_dist = abs(playerc_x - mousepos.x); //get the x and y distance between
double y_dist = abs(playerc_y - mousepos.y); //body and mouse

int mousedist = sqrt((x_dist * x_dist) + (y_dist * y_dist)); //define mouse distance

if (mousedist < REACH){ //If within bounds of reach, follow the mouse position exactly
    fist_x = mousepos.x;
    fist_y = mousepos.y;
}
else{
    fist_x = mousepos.x - (mousepos.x - fist_x); //Otherwise it cannot leave the 
    fist_y = mousepos.y - (mousepos.y - fist_y); //maximum reach
}
return;

}

我现在面临的主要问题是,当角色移动到关卡时,当玩家走得太远时,手会留在后面并锁定到位。 我也喜欢在距离达到REACH后继续移动的第一个物体,但是要保持在规定的距离内“圆圈”。跟随相对的鼠标位置,但我很难在脑海中创建逻辑。任何有经验的家伙都可以给予的帮助非常感谢!

2 个答案:

答案 0 :(得分:1)

void FistPosition(int& player_x,int& player_y, int& fist_x, int& fist_y){ //Start
    ALLEGRO_MOUSE_STATE mousepos;
    al_get_mouse_state(&mousepos); //Get the mouse's x and y position

    const int REACH = 150; //Define the maximum distance the fist can go.

    int playerc_x = player_x + 62; //Define the x and y center of the player object
    int playerc_y = player_y + 92;

    double x_dist = mousepos.x - playerc_x; //get the x and y distance between
    double y_dist = mousepos.y - playerc_y; //body and mouse

    int mousedist = sqrt((x_dist * x_dist) + (y_dist * y_dist)); //define mouse distance

    if (mousedist < REACH){ //If within bounds of reach, follow the mouse position exactly
        fist_x = mousepos.x;
        fist_y = mousepos.y;
    }
    else{
        double angle = atan2(y_dist/xdist);  //work out the angle to the mouse
        fist_x = playerc_x + REACH*cos(angle);
        fist_x = playerc_y + REACH*sin(angle);
    }
    return;
}

我做了一些改变:

  1. 删除了abs()功能,并更改了x_disty_dist作业中的字词顺序。不需要绝对值(x*x总是正数),现在它代表距离和方向(+ x在右边等)。
  2. 添加了对鼠标的角度计算
  3. 最大到达时fist的计算位置
  4. 详细说明:

    2:atan2与标准atan函数不同,返回表示输入描述的扇区的角度。这允许我们使用像'135 degees'这样的角度,而不是必须在角度所在的位置(从原点顺时针方向的第2扇区)处理,并为每个扇区增加90度。 3:使用sin和cos

    计算半径= REACH的位置

    使用这些fist应该继续前进。

    之前没有:

    fist_x = mousepos.x - (mousepos.x - fist_x);
    fist_y = mousepos.y - (mousepos.y - fist_y);
    

    mousepos条款取消,所以它只是:

    //this line:      mousepos.x - (mousepos.x - fist_x); 
    //is the same as: mousepos.x - mousepos.x + fist_x;
    fist_x = fist_x;
    fist_y = fist_y;
    

答案 1 :(得分:0)

在极坐标中思考可能更好。将鼠标位置与肩部位置进行比较,以获得所需的角度和半径。将半径夹到REACH,然后转换回直角坐标。