默认情况下,我在程序中使用的图像中的恐龙面朝左,但如果用户按下右键,它应该向右翻转,当他反复按右键时,它应该向右移动。当恐龙面向右侧时按下左键,它应向左翻转,当他按下左键时,恐龙应向左移动。我尝试了以下代码,但它没有用。
private void moveDinos(object sender, KeyEventArgs e)
{
bool lturn = false;
if (e.KeyCode == Keys.Left && titlePic.Visible == false)
{
if (lturn == true)
dino.Image.RotateFlip(RotateFlipType.Rotate180FlipY);
dino.Left -= 100;
}
else if (e.KeyCode == Keys.Right && titlePic.Visible == false)
{
if (lturn == false)
dino.Image.RotateFlip(RotateFlipType.Rotate180FlipY);
dino.Left += 100;
}
}
我尝试了很多东西,但我似乎无法理解逻辑。
答案 0 :(得分:0)
你的lturn布尔值是确定dino面向的方向?它需要从方法中走出来并进入课堂:
private bool _lturn = true;
然后可以在你的逻辑中使用它,因为它并不总是错误的:
private void moveDinos(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left && titlePic.Visible == false)
{
if (_lturn != true)
{
dino.Image.RotateFlip(RotateFlipType.Rotate180FlipY);
_lturn = true;
}
else
{
dino.Left -= 100;
}
}
else if (e.KeyCode == Keys.Right && titlePic.Visible == false)
{
if (_lturn == true)
{
dino.Image.RotateFlip(RotateFlipType.Rotate180FlipY);
_lturn = false;
}
else
{
dino.Left += 100;
}
}
}
所以if语句也发生了变化:
答案 1 :(得分:0)
你必须跟踪它面对的当前一面。 (存储在字段中)如果用户再次按下左侧,则不应再次翻转。
类似的东西:
private bool _facingLeft; // initial state of the image must match with this boolean.
private void moveDinos(object sender, KeyEventArgs e)
{
// this shoudn't depend on the visible state of the title!!! you should change it.
if(titlePic.Visible)
return;
// check the keys if the left or right key is pressed.
if((e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Right))
{
// when the left button is pressed, it should face left..
bool moveToTheLeft = (e.KeyCode == Keys.Left);
// if the current state of the image facing the wrong direction?
if(_facingLeft != moveToTheLeft)
{
// if not, flip the image.
dino.Image.RotateFlip(RotateFlipType.Rotate180FlipY);
// store the current facing.
_facingLeft = moveToTheLeft;
}
else
// move the dino..
if(moveToTheLeft)
dino.Left -= 100;
else
dino.Left += 100;
}
}