我正在制作一个 2d 自上而下的游戏,玩家控制一只猫。为此,该人使用 WASD 键移动。我有 Form1、GameManager、Cat 和 Moveable 类。Form1 向 GameManager 发送 cat imagelist 和 e.graphics(用于图片框)。GameManager 有一个计时器,每次滴答都会检查猫是否移动了。Cat 处理移动逻辑。当我运行程序时,猫精灵出现在它的初始位置,但在按下键时不会移动。我无法弄清楚我的问题,有人可以帮忙吗?
这是我的课程:
表格1:
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)
{
p.Y = p.Y - n;
}
if (dir == 1)
{
p.X = p.X + n;
}
if (dir == 2)
{
p.Y = p.Y + n;
}
if (dir == 3)
{
p.X = p.X - 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 事件,这样它就知道它面对的方向,所以它知道要移动的方向。