为什么我的图像不会移动?

我正在制作一个2D自上而下的游戏,玩家控制着一只猫。 为此,此人使用WASD键移动。 我有Form1,GameManager,Cat和Moveable类。 Form1向GameManager发送cat imagelist和e.graphics(用于图片框)。 GameManager有一个计时器,每个勾选检查猫是否已经移动。 Cat处理移动逻辑。 当我运行程序时,cat精灵显示在其初始位置,但是在按下键时不会移动。 我无法弄清楚我的问题,有人可以帮忙吗?

这是我的课程:

Form1中:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CatAndMouse { public partial class Form1 : Form { GameManager myGM = new GameManager(); public Form1() { InitializeComponent(); newGame(); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if (this.myGM != null) this.myGM.paint(e.Graphics); } public void newGame() { myGM.newGame(imgCat); } } } 

游戏管理:

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CatAndMouse { class GameManager { Cat ca1 = new Cat(); int amount = 5; Timer time = new Timer(); public ImageList imgCat = new ImageList(); public void newGame(ImageList cat) { imgCat = cat; time.Start(); } public void move() { ca1.Move(amount); } public void paint(Graphics g) { g.DrawImage(imgCat.Images[0], ca1.getLocation()); } private void time_Tick(object sender, EventArgs e) { move(); } } } 

猫:

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CatAndMouse { class Cat: Moveable { Random myCLoc = new Random(); private Moveable myCatMove; public Point p = new Point(100, 100); int dir = 0; public void Move(int n) { if (dir == 0) { pY = pY - n; } if (dir == 1) { pX = pX + n; } if (dir == 2) { pY = pY + n; } if (dir == 3) { pX = pX - n; } } private void KeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.Up) { dir = 0; } if (e.KeyCode == Keys.Right) { dir = 1; } if (e.KeyCode == Keys.Down) { dir = 2; } if (e.KeyCode == Keys.Left) { dir = 3; } } public void changeDirection() { } public Point getLocation() { return p; } public void paint(PaintEventArgs e) { } } } 

活动:

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CatAndMouse { public interface Moveable { void Move(int n); void changeDirection(); //Point getLocation(); void paint(PaintEventArgs e); } } 

所以,我没有任何调用KeyDown()的东西。 如果需要KeyEventArgs e,如何调用KeyDown()?

Picturebox1没有keydown事件,form1也没有。 我还需要在cat类中使用keydown事件,因此它知道它面向的方向,因此它知道要移动的方向。

  1. 您的代码中没有键盘事件。 可能是你把它遗漏了(已经有太多的代码)但是后来说了些什么。

  2. 每次move()您需要Invalidate()相关的Control,在本例中为PictureBox。

您的课程中没有任何内容可以获得有关keydown事件的通知。

你的form1类应该有keydown的处理程序,你在那里实现移动逻辑,或者你的Cat类应该派生自System.Windows.Forms.Control,在那里实现keydown处理程序。

然后,一旦新控件Cat具有焦点,就会在您的控件上引发按键事件。