使对象跟随鼠标

Make Objects Follow Mouse

本文关键字:鼠标 跟随 对象      更新时间:2023-10-16

与此主题相关的其他问题似乎对我理解不太有帮助。我刚开始使用Visual Studio和Direct2D编程,我很难理解如何让两个"眼睛"(椭圆中的椭圆)跟随我的鼠标。

在函数void MainWindow::CalculateLayout()内部,我正在使用

    const float radius3=radius/4;
    const float radius3_2=radius/5;
    const float x3=x-100;
    const float y3=y-150;
    ellipse3 = D2D1::Ellipse(D2D1::Point2F(x3, y3), radius3, radius3_2);
        //left eye
    const float radius4=radius/4;
    const float radius4_2=radius/5;
    const float x4=x+100;
    const float y4=y-150;
    ellipse4 = D2D1::Ellipse(D2D1::Point2F(x4, y4), radius4, radius4_2);
        //right eye
    const float radius5=radius/8;
    const float radius5_2=radius5/2;
    const float x5=x-100;
    const float y5=y-150;
    ellipse5 = D2D1::Ellipse(D2D1::Point2F(x5, y5), radius5, radius5_2);    
    // left eyeball
    const float radius6=radius/8;
    const float radius6_2=radius6/2;
    const float x6=x+100;
    const float y6=y-150;
    ellipse6 = D2D1::Ellipse(D2D1::Point2F(x6, y6), radius6, radius6_2);    
    // right eyeball

设置眼睛和眼球所在的位置。我认为应该使用类似的东西来控制鼠标的位置。我正试图从一个空白项目中而不是从表单中进行此操作。解决方案是简单地将const float x5=x-100替换为MouseMoveX值吗?

您需要替换x5的定义,但需要使用一个公式来将其绑定到眼球内。

你的公式看起来像这样:

// compute the angle from the eyes to the mouse
angle = arctan( (mouseY - y) / (mouseX - x) );
// x-100 and y-150 are assumed to be the origins (center) of the eyeball
// eyeballRadius should be the radius of the eyeball, or slightly smaller (so the eyes do not extend outside of it)
x5 = (x-100) + cos(angle) * eyeballRadius;
y5 = (y-150) + sin(angle) * eyeballRadius;

希望这能有所帮助。

当光标非常靠近时,要获得斗鸡眼效果,应该让每个眼球计算自己的角度,例如左侧的角度为leftAngle = arctan( (mouseY - (y-150)) / (mouseX - (x-100)) )