1 回答

TA貢獻1826條經驗 獲得超6個贊
有一種觀點與你的代碼不正確,至少我認為是這樣。
你總是把球員移動到他的新位置。你一定要檢查他是否觸及了界限。如果他觸及邊界,你把他向上移動一個像素,向左移動一個像素,只是為了將他移動到7個像素到所選的direktion中。因此,在你檢查他是否觸及邊界的地方,你必須中斷,不要執行設置新位置的其余代碼。一個簡單的將完成這項工作。
if
return;
如果按下一個鍵,你將進行邊界檢查,如果玩家沒有觸及邊界,你將移動玩家。這是錯誤的順序。你必須檢查玩家在移動后是否會觸及邊界,只有當他不會觸摸邊界移動他時。否則,你會把他移入邊界,再也不把他趕出去。
所以這是你的代碼和一些更正:
private void HorrorForm_KeyDown(object sender, KeyEventArgs e)
{
int x = player.Location.X;
int y = player.Location.Y;
if (e.KeyCode == Keys.D)
x += 7;
if (e.KeyCode == Keys.A)
x -= 7;
if (e.KeyCode == Keys.S)
y += 7;
if (e.KeyCode == Keys.W)
y -= 7;
var tempPlayerPosition= player.Bounds; // get the players position and remember it temporary
tempPlayerPosition.X = x; // change the players temporary pisition to the new one that it will have after the move
tempPlayerPosition.Y = y;
//check if the play would touch the boundyries if we use the new temporary pisition
if (tempPlayerPosition.IntersectsWith(openspot1.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot2.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot3.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot4.Bounds))
{
return; //if he would touch the boundary, then do nothing
}
player.Location = new Point(x, y); //if he would not touch the boundary, move him to his new location
}
但也許你也想
防止在按下不是 W、S、A 或 D 的鍵時執行代碼(即使他沒有改變任何值)。
使用而不是這樣使它更具可讀性。
switch
if
而不是每次都寫數字7,使用局部變量,所以如果將來會改變,你只需要改變一個值。
所以我的建議是這樣的:
private void HorrorForm_KeyDown(object sender, KeyEventArgs e)
{
var oneStep = 7; // define the amount of pixel the player will be moved
var tempPlayerPosition = player.Bounds;// get the players position and remember it temporary
switch (e.KeyCode) // check which key was presses
{
case Keys.D:
tempPlayerPosition.X += oneStep; // move right
break;
case Keys.A:
tempPlayerPosition.X -= oneStep; // move left
break;
case Keys.S:
tempPlayerPosition.Y += oneStep; // move down
break;
case Keys.W:
tempPlayerPosition.Y -= oneStep; // move up
break;
default: // you may wan't to do nothing if there any other key presses...
return;
}
//check if the play would touch the boundyries if we use the new temporary pisition
if (tempPlayerPosition.IntersectsWith(openspot1.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot2.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot3.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot4.Bounds))
{
return; //if he would touch the boundary, then do nothing
}
player.Location = new Point(tempPlayerPosition.X, tempPlayerPosition.Y); //if he would not touch the boundary, move him to his new location
}
這對你有幫助嗎?
- 1 回答
- 0 關注
- 96 瀏覽
添加回答
舉報