2015-04-02 71 views
0

我已经开始一个新项目,并决定首先执行程序中最难的部分,当我说最难的时候我的意思是那些恶作剧。尝试更正“播放器”跟随控制(光标)的位置

下面的代码让我的播放器跟随鼠标光标,但是移动是固定的,而且播放器的位置是相对于光标位置到屏幕而不是实际的节目窗口。窗口越靠近屏幕光标和播放器变得越近。

我正在寻找帮助来纠正这种情况,以便玩家的位置以一定的速度移动到游标的位置,但实际上跟随指针。

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); 
      } 
     } 
    } 
} 

回答

0

这听起来像你想要的是Point 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)); 
+0

Console.WriteLine();在WinForms?....... – 2015-04-02 13:55:05

+0

是的,对此有所评论。我忘了不是每个人都在使用visual studio及其输出视图进行调试。您也可以在表单上放置两个标签,并相应地更改它们的文本值... – Toastgeraet 2015-04-02 18:51:47

+0

@Toastgeraet您也可以使用'System.Diagnostics.Debug.WriteLine';) – Icepickle 2015-04-04 13:44:26