2016-08-04 64 views
-4
double bullet::distance(int x1, int y1, int x2, int y2) 
{ 
    return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); 
} 

距离函数^拍摄子弹用鼠标

speedX.push_back((x - targetx)/distance(x, y, targetx, targety)*7);//x player pos, targetx mouse pos 
speedY.push_back((y - targety)/distance(x, y, targetx, targety)*7); 

计算的像素数量如何变化每隔8ms^

sbullet[i].setX(sbullet[i].getX() - (int)round(speedX[i])); 
sbullet[i].setY(sbullet[i].getY() - (int)round(speedY[i])); 

实际移动^

所以这是我的子弹用鼠标去,但它并不完全适用于鼠标。

我该如何让它更加准确?

+0

“___但它是相当不准确的。”你能跟我们分享你所见证的吗?你是什​​么意思“_it有时命中mouse_”?还有像'x-targetx'和'sbullet [i] .getX() - (int)round(speedX [i])'而不处理'negative'异常是一个问题,你确定你需要它是不是**绝对值**? –

+1

撇开 - 计算笛卡尔距离更方便的方法是使用['std :: hypot'](http://en.cppreference.com/w/cpp/numeric/math/hypot)。所以在你的情况下这将是'std :: hypot(x2-x1,y2-y1)'。 – ArchbishopOfBanterbury

+0

它并不完全适用于鼠标,它缺少它,如果你仍然不明白我可以下载游戏,如果你想要:/ – lollypap54

回答

1

你需要放慢速度,一旦你到达鼠标。在你的代码中,你总是向目标方向移动7个像素。如果距离不到7个像素,则会超调。

您可以添加一条语句,如果距离小于7,只需将新位置设置为目标。