[英]Attempting to correct the position from which the “player” follows the control(cursor)
我已經開始了一個新項目,並決定首先做程序中最難的部分,當我最難地說時,我的意思是the瑣。
下面的代碼使我的播放器跟隨鼠標光標移動,但其移動是恆定的,並且播放器的位置是相對於光標在屏幕上而不是在實際程序窗口中的位置。窗口越靠近屏幕上角,則其越靠近光標和播放器成為。
我正在尋求幫助來更正此問題,以便玩家的位置以一定速度移至光標的位置,但實際上跟隨指針。
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);
}
}
}
}
聽起來您想要的是方法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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.