【问题标题】:Attempting to correct the position from which the "player" follows the control(cursor)试图纠正“玩家”跟随控件的位置(光标)
【发布时间】:2018-07-29 08:38:35
【问题描述】:

我已经开始了一个新项目,并决定先完成程序中最难的部分,当我说最难时,我指的是琐碎的部分。

下面的代码让我的播放器跟随鼠标光标,但移动是恒定的,播放器的位置是相对于光标在屏幕上的位置而不是实际的程序窗口。窗口越靠近屏幕的上角光标和播放器越接近。

我正在寻求帮助来纠正这个问题,以便玩家的位置以一定的速度移动到光标处,但实际上跟随指针。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace games1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public void Form1_Click(object sender, MouseEventArgs e)
        {
                Invalidate();
        }
       private void tmrMoving_Tick_1(object sender, EventArgs e)
        {
            if (tmrMoving.Enabled == true)
        {
            var cursPoint = new System.Drawing.Point(Cursor.Position.X, Cursor.Position.Y);
            var playerPoint = new System.Drawing.Point(player.Location.X, player.Location.Y);
            var diff = new Point(Cursor.Position.X - playerPoint.X, Cursor.Position.Y - playerPoint.Y);
            var speed = Math.Sqrt(diff.X * diff.X + diff.Y * diff.Y);
            if (speed > 10)
            {
                diff.X /= (int)(speed / 10);
                diff.Y /= (int)(speed / 10);
            }
            player.Location = new System.Drawing.Point(player.Location.X + diff.X, player.Location.Y + diff.Y);
            }
        }
    }
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    听起来你想要的是方法 PointToClient()。

    您可以在控件上调用它。例如,如果您在表单上调用它,则可以使用它将光标的位置(相对于屏幕)转换为相对于表单(在本例中为客户端)的点。

    要探索此行为,您可以使用空表单创建一个新的空项目,并将表单的 MouseUp-Event 绑定到此处理程序。

        public Form1()
        {
            InitializeComponent();
            this.MouseUp += new MouseEventHandler(Form1_MouseUp);
        }
    
        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            Console.WriteLine("X: " + Cursor.Position.X + " - Y: " + Cursor.Position.Y);
            var goodCoordinates = PointToClient(Cursor.Position);
            Console.WriteLine("X: " + goodCoordinates.X + " - Y: " + goodCoordinates.Y);
        }
    

    您需要像这样更正您的代码:

    var cursPoint = PointToClient(new System.Drawing.Point(Cursor.Position.X, Cursor.Position.Y));
    

    【讨论】:

    • 是的,对不起。我忘记了不是每个人都在使用 Visual Studio 及其输出视图进行调试。您也可以改为在表单上放置两个标签并相应地更改它们的文本值...
    • @Toastgeraet 你也可以使用System.Diagnostics.Debug.WriteLine ;)
    • 谢谢icepickle。我将来会尝试使用这种技术来提高我的代码质量。显然我的方法不是很清楚,比较粗略。
    猜你喜欢
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多