当前位置:K88软件开发文章中心编程语言.NET.NET01 → 文章内容

用C#编写物体碰撞的程序

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2018-12-31 11:48:38

:2010-09-10 07:38:00

本文讲解了使用C#编写物体碰撞的一个源代码,本实例来自一个老外的网站,从源代码就可以看出,编写的很专业,大家可以学一学。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Form1 : System.Windows.Forms.Form {
    private int dx = 4;
    private System.Windows.Forms.PictureBox picTarget;
    private System.Windows.Forms.PictureBox picBall;
    private System.Windows.Forms.Timer timer1;

    public Form1() {
        InitializeComponent();
    }
    private void InitializeComponent() {
      this.picTarget = new System.Windows.Forms.PictureBox();
      this.picBall = new System.Windows.Forms.PictureBox();
      this.timer1 = new System.Windows.Forms.Timer(new System.ComponentModel.Container());
      this.SuspendLayout();

      this.picTarget.BackColor = Color.Red;
      this.picTarget.Location = new System.Drawing.Point(160240);
      this.picTarget.Name = "picTarget";
      this.picTarget.Size = new System.Drawing.Size(5656);
      this.picTarget.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
      this.picTarget.TabIndex = 0;
      this.picTarget.TabStop = false;

      this.picBall.Image = new Bitmap("winter.jpg");
      this.picBall.Location = new System.Drawing.Point(24136);
      this.picBall.Name = "picBall";
      this.picBall.Size = new System.Drawing.Size(3232);
      this.picBall.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
      this.picBall.TabIndex = 1;
      this.picBall.TabStop = false;

      this.timer1.Enabled = true;
      this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

      this.AutoScaleBaseSize = new System.Drawing.Size(513);
      this.BackColor = System.Drawing.Color.White;
      this.ClientSize = new System.Drawing.Size(392341);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                  this.picBall,
                                                                  this.picTarget});
      this.Name = "Form1";
      this.Text = "Crasher";
      this.ResumeLayout(false);

    }
    [STAThread]
    static void Main() {
      Application.Run(new Form1());
    }

    private void timer1_Tick(object sender, System.EventArgs e) {
      int newX, newY;
      newX = picBall.Location.X + dx;
      newY = picBall.Location.Y + dx;
      
      if (newX > this.Width - picBall.Width){
        dx = - dx;
      
      
      if (newX < 0){
        dx = - dx;
      }
      
      if (picBall.Bounds.IntersectsWith(picTarget.Bounds)){
        this.BackColor = Color.Black;
      else {
        this.BackColor = Color.White;
      }
      
      picBall.Location = new Point(newX, newY);
    }
}



用C#编写物体碰撞的程序