[C#]键盘↑↓←→控制图片加速移动

想做简单游戏的同学们可以学习一下。

[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);
        }

    }
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值