Rectangle r1 = pictureBox1.DisplayRectangle;
Rectangle r2 = pictureBox2.DisplayRectangle;
r1.Location = pictureBox1.Location;
r2.Location = pictureBox2.Location;
if (r1.IntersectsWith(r2))
//столкновение
Ну вы предоставили код с ответом на ваш вопрос, что не так?
//Создаем элементы
PictureBox[] arr = new PictureBox[10];
Random rnd = new Random();
for (int i = 0; i < arr.Length; i++){
arr[i] = new PictureBox();
arr[i].Width = 30;
arr[i].Height= 30;
var bmp = new Bitmap(arr[i].Width, arr[i].Height);
using (Graphics gfx = Graphics.FromImage(bmp))
using (SolidBrush brush = new SolidBrush(Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255))))
gfx.FillRectangle(brush, 0, 0, bmp.Width, bmp.Height);
arr[i].Image = bmp;
arr[i].Left = i*100;
this.Controls.Add(arr[i]);
}
//Проверяем столкновения каждого с каждым
for (int i = 0; i < arr.Length; i++)
for (int j = i; j < arr.Length; j++)
if (j != i &&
arr[i].Left + arr[i].Width >= arr[j].Left && arr[i].Left <= arr[j].Left + arr[j].Width &&
arr[i].Top + arr[i].Height >= arr[j].Top && arr[i].Top <= arr[j].Top + arr[j].Height)
Console.WriteLine("Пересечение " + i + " и " + j);
arr[0] = pictureBox1;
arr[1] = pictureBox2;
arr[2] = pictureBox3;
public partial class Form1 : Form
{
private double speedX = 0;
private double speedY= 0;
private double speed = 5;//скорость движения
private double jump= 12;//сила прыжка
private double gravityForce= 0.05f;//Ускорение свободного падения
private double gravitySpeed= 0;//сила гравитации
private bool isGround = true;//За земли ли игрок
public Form1() {
InitializeComponent();
PictureBox[] obstacles = new PictureBox[] {
left_wall,
right_wall,
floor,
roof,
platform1,
platform2,
platform3
};
KeyDown += Form1_KeyDown;
KeyUp += Form1_KeyUp;
Task.Run(() =>
{
while (true) {
Invoke(new Action(() => {
//для управщения сначала двигаем по х, и проверяем всё, а потом по у и опять всё проверяем
player.Left += Convert.ToInt32(speedX);//Двинули по x
if(speedX!= 0)
for (int i = 0; i < obstacles.Length; i++)
{
if (player.Left + player.Width > obstacles[i].Left &&
player.Left < obstacles[i].Left + obstacles[i].Width &&
player.Top + player.Height > obstacles[i].Top &&
player.Top < obstacles[i].Top + obstacles[i].Height) {//Проверка столкновения с препятствием
if (speedX > 0)//Если мы двигались вправо, то выталкиваем игрока за левую границу объекта с которым столкнулись
player.Left = obstacles[i].Left - player.Width;
else//Иначе если мы двигались влево, то выталкиваем игрока за правую границу объекта с которым столкнулись
player.Left = obstacles[i].Left + obstacles[i].Width;
}
}
gravitySpeed += gravityForce;//добавляем ускорение свободного падения к текущей гравитации
speedY -= gravitySpeed;
player.Top -= Convert.ToInt32(speedY);//Двинули по у
for (int i = 0; i < obstacles.Length; i++) {
if (player.Left + player.Width > obstacles[i].Left &&
player.Left < obstacles[i].Left + obstacles[i].Width &&
player.Top + player.Height > obstacles[i].Top &&
player.Top < obstacles[i].Top + obstacles[i].Height) {//Проверка столкновения с препятствием
if (speedY > 0)//Если мы двигались вверх, то выталкиваем игрока за нижнюю границу объекта с которым столкнулись
player.Top = obstacles[i].Top + obstacles[i].Height;
else {//Если мы двигались вниз(падаем), то выталкиваем игрока за верхнюю границу объекта с которым столкнулись, и заодно говорим что стоим на земле
player.Top = obstacles[i].Top - player.Height;
isGround = true;
}
gravitySpeed = 0;//Если врезали головой или ногами то обнуляем гравитацию
speedY = 0;
}
}
}));
Thread.Sleep(1000 / 60);
}
});
}
private void Form1_KeyUp(object sender, KeyEventArgs e){
if (e.KeyCode == Keys.D && speedX > 0)
speedX = 0;
if (e.KeyCode == Keys.A && speedX < 0)
speedX = 0;
}
private void Form1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.D)
speedX = speed;
if (e.KeyCode == Keys.A)
speedX = -speed;
if (e.KeyCode == Keys.W && isGround) {
speedY = jump;
isGround = false;
}
}
}
partial class Form1
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.player = new System.Windows.Forms.PictureBox();
this.floor = new System.Windows.Forms.PictureBox();
this.left_wall = new System.Windows.Forms.PictureBox();
this.right_wall = new System.Windows.Forms.PictureBox();
this.roof = new System.Windows.Forms.PictureBox();
this.platform1 = new System.Windows.Forms.PictureBox();
this.platform2 = new System.Windows.Forms.PictureBox();
this.platform3 = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.player)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.floor)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.left_wall)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.right_wall)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.roof)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.platform1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.platform2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.platform3)).BeginInit();
this.SuspendLayout();
//
// player
//
this.player.BackColor = System.Drawing.Color.Red;
this.player.Location = new System.Drawing.Point(366, 139);
this.player.Name = "player";
this.player.Size = new System.Drawing.Size(67, 133);
this.player.TabIndex = 0;
this.player.TabStop = false;
//
// floor
//
this.floor.BackColor = System.Drawing.Color.DimGray;
this.floor.Location = new System.Drawing.Point(92, 546);
this.floor.Name = "floor";
this.floor.Size = new System.Drawing.Size(1143, 50);
this.floor.TabIndex = 1;
this.floor.TabStop = false;
//
// left_wall
//
this.left_wall.BackColor = System.Drawing.SystemColors.Highlight;
this.left_wall.Location = new System.Drawing.Point(92, 102);
this.left_wall.Name = "left_wall";
this.left_wall.Size = new System.Drawing.Size(32, 451);
this.left_wall.TabIndex = 2;
this.left_wall.TabStop = false;
//
// right_wall
//
this.right_wall.BackColor = System.Drawing.SystemColors.Highlight;
this.right_wall.Location = new System.Drawing.Point(1189, 102);
this.right_wall.Name = "right_wall";
this.right_wall.Size = new System.Drawing.Size(32, 451);
this.right_wall.TabIndex = 3;
this.right_wall.TabStop = false;
//
// roof
//
this.roof.BackColor = System.Drawing.SystemColors.ControlLight;
this.roof.Location = new System.Drawing.Point(92, 70);
this.roof.Name = "roof";
this.roof.Size = new System.Drawing.Size(1129, 35);
this.roof.TabIndex = 4;
this.roof.TabStop = false;
//
// platform1
//
this.platform1.BackColor = System.Drawing.Color.Yellow;
this.platform1.Location = new System.Drawing.Point(588, 445);
this.platform1.Name = "platform1";
this.platform1.Size = new System.Drawing.Size(184, 38);
this.platform1.TabIndex = 5;
this.platform1.TabStop = false;
//
// platform2
//
this.platform2.BackColor = System.Drawing.Color.Yellow;
this.platform2.Location = new System.Drawing.Point(879, 373);
this.platform2.Name = "platform2";
this.platform2.Size = new System.Drawing.Size(184, 38);
this.platform2.TabIndex = 6;
this.platform2.TabStop = false;
//
// platform3
//
this.platform3.BackColor = System.Drawing.Color.Yellow;
this.platform3.Location = new System.Drawing.Point(999, 278);
this.platform3.Name = "platform3";
this.platform3.Size = new System.Drawing.Size(184, 38);
this.platform3.TabIndex = 7;
this.platform3.TabStop = false;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label1.Location = new System.Drawing.Point(264, 220);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(201, 25);
this.label1.TabIndex = 8;
this.label1.Text = "Управление WASD";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1233, 646);
this.Controls.Add(this.label1);
this.Controls.Add(this.platform3);
this.Controls.Add(this.platform2);
this.Controls.Add(this.platform1);
this.Controls.Add(this.roof);
this.Controls.Add(this.right_wall);
this.Controls.Add(this.left_wall);
this.Controls.Add(this.floor);
this.Controls.Add(this.player);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.player)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.floor)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.left_wall)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.right_wall)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.roof)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.platform1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.platform2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.platform3)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox player;
private System.Windows.Forms.PictureBox floor;
private System.Windows.Forms.PictureBox left_wall;
private System.Windows.Forms.PictureBox right_wall;
private System.Windows.Forms.PictureBox roof;
private System.Windows.Forms.PictureBox platform1;
private System.Windows.Forms.PictureBox platform2;
private System.Windows.Forms.PictureBox platform3;
private System.Windows.Forms.Label label1;
}
public partial class Form1 : Form
{
PictureBox[] ObjectsLevel1;
Rectangle[] Objects;
Rectangle PlayerRectangle;
public Form1()
{
InitializeComponent();
ObjectsLevel1 = new PictureBox[]
{
pictureBox1,
pictureBox2,
pictureBox3,
pictureBox4,
pictureBox5,
pictureBox6,
pictureBox7,
Roof,
Paul,
pictureBox8,
pictureBox9
};
Objects = new Rectangle[ObjectsLevel1.Length];
for (int i = 0; i < ObjectsLevel1.Length; i++)
{
Objects[i] = ObjectsLevel1[i].DisplayRectangle;
Objects[i].Location = ObjectsLevel1[i].Location;
}
PlayerRectangle = Player.DisplayRectangle;
}
bool isGround = false;
double MoveX = 0, MoveY = 0, gravitySpeed = 0;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D)
{
MoveX = 5;
}
if (e.KeyCode == Keys.A)
{
MoveX = -5;
}
if (e.KeyCode == Keys.W && isGround == true)
{
MoveY = 7;
isGround = false;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D && MoveX > 0)
{
MoveX = 0;
}
if (e.KeyCode == Keys.A && MoveX < 0)
{
MoveX = 0;
}
}
private void PlayerController_Tick(object sender, EventArgs e)
{
if (MoveX != 0)
{
Player.Left += Convert.ToInt32(MoveX);
PlayerRectangle.Location = Player.Location;
for (int i = 0; i < Objects.Length; i++)
{
if (PlayerRectangle.IntersectsWith(Objects[i]))
{
Player.Left -= Convert.ToInt32(MoveX);
}
}
}
MoveY -= 0.1;
Player.Top -= Convert.ToInt32(MoveY);
PlayerRectangle.Location = Player.Location;
for (int i = 0; i < Objects.Length; i++)
{
if (PlayerRectangle.IntersectsWith(Objects[i]) || Player.Location.Y == 790)
{
if (MoveY > 0)
{
Player.Top = Objects[i].Top + Objects[i].Height;
}
else
{
Player.Top = Objects[i].Top - Player.Height;
isGround = true;
}
gravitySpeed = 0;
MoveY = 0;
}
}
label1.Text = "X = " + Player.Location.X + " Y = " + Player.Location.Y + "\nMoveY = " + MoveY + "\nisGround = " + isGround;
}
}
if (PlayerRectangle.IntersectsWith(Objects[i]) || Player.Location.Y == 790)
|| Player.Location.Y == 790