想做简单游戏的同学们可以学习一下。
[C#]键盘控制图片移动(10秒)
源码
using System;
using System.Drawing;
using System.Windows.Forms;
namespace 键盘控制移动CS {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
int 左右;
int 上下;
double X;
double Y;
double VX;
double VY;
double 加速度;
Timer 时钟 = new Timer();
Label 移动控件 = new Label();
private void Form1_Load(object sender, EventArgs e) {
this.KeyPreview = true;
加速度 = 0.5;
X = 300.0;
Y = 300.0;
移动控件.BackColor = Color.MediumPurple;
移动控件.Size = new Size(60, 60);
Controls.Add(移动控件);
KeyDown += Form1_KeyDown;
KeyUp += Form1_KeyUp;
时钟.Tick += 时钟_Tick;
时钟.Interval = 25;
时钟.Enabled = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Up)
上下 = -1;
if (e.KeyCode == Keys.Down)
上下 = 1;
if (e.KeyCode == Keys.Left)
左右 = -1;
if (e.KeyCode == Keys.Right)
左右 = 1;
}
private void Form1_KeyUp(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Up)
上下 = 0;
if (e.KeyCode == Keys.Down)
上下 = 0;
if (e.KeyCode == Keys.Left)
左右 = 0;
if (e.KeyCode == Keys.Right)
左右 = 0;
}
private void 时钟_Tick(object sender, EventArgs e) {
VX = Math.Min(VX + 左右 * 加速度, 10);
VY = Math.Min(VY + 上下 * 加速度, 10);
X += VX;
Y += VY;
if (X < 0) { X = 2; VX = -VX; }
if (Y < 0) { Y = 2; VY = -VY; }
int 右边界 = ClientSize.Width - 移动控件.Width;
int 下边界 = ClientSize.Height - 移动控件.Height;
if (X > 右边界) { X = 右边界 - 2; VX = -VX; }
if (Y > 下边界) { Y = 下边界 - 2; VY = -VY; }
移动控件.Location = new Point((int)X, (int)Y);
}
}
}