2015-04-02 46 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