当计时器滴答时,将图片框移动到随机X和Y.

时间:2013-04-06 15:17:10

标签: c#

我有这个名为obstaclePicture的pictureBox,当我的计时器(obstacleTimer)打勾时,我想移动到一个新的随机X和Y位置。

它移动的关键在于它是我制作的游戏中的一个障碍。

表格1025; 545px大。

2 个答案:

答案 0 :(得分:4)

假设您的图片框尺寸为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;
        }
    }
}

答案 1 :(得分:1)

尝试这样的事情:

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

    }