1

我有一个名为 barrierPicture 的图片框,当我的计时器 (obstacleTimer) 滴答作响时,我想将其移动到一个新的随机 X 和 Y 位置。

它移动的意义在于它是我制作的游戏中的障碍。

表格的 1025;545px 大。

4

2 回答 2

3

假设您的图片框尺寸为 100x100 像素。timer1 应该被启用

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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public Random r = new Random();
        private void timer1_Tick(object sender, EventArgs e)
        {
            int x = r.Next(0,925);
            int y = r.Next(0,445);
            pictureBox1.Top = y;
            pictureBox1.Left = x;
        }
    }
}
于 2013-04-06T15:26:55.017 回答
0

尝试这样的事情:

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            tm.Interval = 100;
            tm.Tick += new EventHandler(tm_Tick);
            tm.Start();
        }
        Timer tm = new Timer();
        void tm_Tick(object sender, EventArgs e)
        {
            pictureBox1.Location = new Point((int)(new Random().Next(0, 1025)), (int)(new Random().Next(0, 545)));
        }

    }

已编辑:您还必须检查您的图片是否在表格内:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            tm.Interval = 1000;
            tm.Tick += new EventHandler(tm_Tick);
            tm.Start();
        }
        Timer tm = new Timer();
        int X = 0;
        int Y = 0;
        void tm_Tick(object sender, EventArgs e)
        {
            X = ((int)(new Random().Next(0, 1025)));
            Y = ((int)(new Random().Next(0, 545)));
            if (X > 1025 - pictureBox1.Width)
            {
                X = 1025 - pictureBox1.Width;
            }
            if (Y > 545 - pictureBox1.Height)
            {
                Y = 545 - pictureBox1.Height;
            }
            pictureBox1.Location = new Point(X, Y);
        }

    }
于 2013-04-06T15:24:56.683 回答