C# Tutorial – Animating Multiple Objects on Windows Form

Full code of how to animate multiple objects in windows form using c# is below


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 Multiple_Moving_Objects_Animation
{
    public partial class Form1 : Form
    {

        int L1x = 5;
        int L1y = 5;

        int L2x = 5;
        int L2y = 5;


        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            //label 1 movement starts
            label1.Left -= L1x; //this will move it horizontally
            label1.Top -= L1y; // this will move it vertically

            if (label1.Left + label1.Width > ClientSize.Width || label1.Left < 0)
            {
                L1x = -L1x; // this will bounce the object from the left or right border
            }

            if (label1.Top + label1.Height > ClientSize.Height || label1.Top < 0)
            {
                L1y = -L1y; // this will bounce the object from top and bottom border
            }

            // label1 movement ends


            // label 2 move starts here

            label2.Left += L2x; //this will move it horizontally
            label2.Top += L2y; // this will move it vertically

            if (label2.Left + label2.Width > ClientSize.Width || label2.Left < 0)
            {
                L2x = -L2x; // this will bounce the object from the left or right border
            }

            if (label2.Top + label2.Height > ClientSize.Height || label2.Top < 0)
            {
                L2y = -L2y; // this will bounce the object from top and bottom border
            }

            // label 2 movement ends here

        }
    }
}




Comments are closed.