我试图用C#编写我的第一款游戏,但目前我陷入了让玩家移动的困境。
我没有看到逻辑上的问题...
当按下W键时,如果播放器实例中的bool变为true,则在发生tickevent并触发player.move()时,它应该上升...
我希望你能在这里帮助我!
我有一个Player类:
class Player : PictureBox
{
private int _playerspeed = 5;
public bool up = false;
public bool down = false;
public bool left = false;
public bool right = false;
public bool pshoot = false;
Game _game;
public Player(Game game)
{
_game = game;
}
public void spawn()
{
this.BackColor = Color.DarkGreen;
this.Size = new Size(20, 20);
this.Left = 540;
this.Top = 580;
this.Tag = "player";
this.Visible = true;
_game.Controls.Add(this);
this.BringToFront();
}
public void move()
{
if (up)
{
this.Top -= _playerspeed;
}
if (down)
{
this.Top += _playerspeed;
}
}
}
还有一个形式如下的类游戏:
public partial class Game : Form
{
Player player;
bool playerUp = false;
bool playerDown = false;
bool playerLeft = false;
bool playerRight = false;
bool playerShoot = false;
public Game()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
player = new Player(this);
btnStart.Visible = false;
player.spawn();
tmrGameloop.Start();
}
private void tmrGameloop_Tick(object sender, EventArgs e)
{
player.move();
txtTick.Text = Convert.ToString(Convert.ToDecimal(txtTick.Text)+ 1);
}
private void Game_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case (Keys.W):
player.up = true;
break;
case (Keys.S):
player.down = true;
break;
}
}
private void Game_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case (Keys.W):
player.up = false;
break;
case (Keys.S):
player.down = false;
break;
}
}
}
答案 0 :(得分:1)
据我了解,只要按下W或S键,您就希望定期移动播放器。 (如重复的按键)
但是,在您的代码中,player.up
和player.down
布尔值从未设置为true!因此,调用move()
似乎无效。
您应对此进行更正,并在keyDown事件上将其设置为true:
private void Game_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case (Keys.W):
player.up = true;
break;
case (Keys.S):
player.down = true;
break;
}
}
答案 1 :(得分:0)
我看到了几个问题。 首先,对于玩家来说,使用枚举会节省很多工作。
喜欢:
public enum Direction{
up,
down,
left,
right,
notMoving
}
您使用图片框的方式错误。为什么在窗体内没有图片框,您可以将播放器吸引到图片框。图片框内部有很多逻辑。
玩家不应参考表格(游戏)。看起来他可以将自己添加到控件中。问题是他可以删除somethig,更改其他玩家/ mpc的某些属性,这就是您要避免的事情,因为它的确很难(几乎是不可能的)来禁止播放器对象
我的解决方案:
class Game{
private Player player;
// constructor etc.
public void picturebox1_paint(object sender, PaintEventArgs e){
Graphics g = e.Graphics;
player.DrawYourSelf(g);
}
}
picturebox1_paint是图片框的绘制事件。如果使用的是Visual Studio,则可以在“事件”选项卡中创建,选择“图片框”->“属性”->“事件(雷声图标)”->“双击画图”。
class Player{
private Direction direction = Direction.notMoving;
private Point position;
// contructor etc.
public void DrawYourSelf(Graphics g){
// here use g to draw to player to picture box
}
}