首页 > 编程 > C# > 正文

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

2023-05-16 12:36:05
字体:
来源:转载
供稿:网友

本文讲解了使用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);
    }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表