C# Tutorial – How to Spawn random game items in 2D and pick them up using collision with C# and Win Forms in Visual Studio
- Subject: C# Tutorials
- Learning Time: 1 hour
Hi in this tutorial we will making improvements to the 4 way sprite movements tutorial. To follow on this please make sure you have finished the last tutorial as we will using the code and set up from the first project. In this tutorial we will add item drop and collection feature. For this feature we will be loading 17 different RPG items and drop them randomly on the screen. We will also add a player and item collision feature in the game. The idea is the player can move around the screen and when they collide with an item it will disappear and update the label with the item name. We will be working in Visual Studio, Windows Forms .Net with C#. Hope you have a fun with this tutorial.
Lesson Objectives:
- Create a Items Class in C# with its own properties such as positionX, positionY, height and width etc.
- Instantiate the class from the main form using custom functions
- Assign names of the items using a string array
- Load external files from the folder to a list and use that list to randomly assign images to the items class
- Create a time limit per item, so they disappear from the screen when their time is over
- Add and remove items dynamically from the list
- Create a player and item collision system
- Remove the items from the game when player collides with the items
- Get the item name and display it on the label in windows forms
Video Tutorial –
Download the items images used in this tutorial
Get C# 4 Way Movement and Item Pick Up Project on GitHub
Source Code –
Items Class Source Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; // created by MOOICT.COM 2023 // for educational purpose only namespace _4_Way_Movement_with_Sprite_Images_MOO_ICT { internal class Items { public int positionX; public int positionY; public Image item_image; public int height; public int width; public string name; Random range = new Random(); int lifeTime = 200; public bool expired = false; public Items() { item_image = Image.FromFile("items/item_01.png"); positionX = range.Next(10, 700); positionY = range.Next(10, 500); height = 50; width = 50; } public void CheckLifeTime() { lifeTime--; if (lifeTime < 1) { expired = true; } } } }
Form1 Class Source Code
namespace _4_Way_Movement_with_Sprite_Images_MOO_ICT { public partial class Form1 : Form { // created by MOOICT.COM // for educational purposes only Image player; List<string> playerMovements = new List<string>(); int steps = 0; int slowDownFrameRate = 0; bool goLeft, goRight, goUp, goDown; int playerX; int playerY; int playerHeight = 100; int playerWidth = 100; int playerSpeed = 8; // items variables List<string> item_locations = new List<string>(); List<Items> items_list = new List<Items>(); int spawnTimeLimit = 50; int timeCounter = 0; Random rand = new Random(); string[] itemNames = { "red sword", "medium armour", "green shoes", "gold lamp", "red potion", "fast sword", "instruction manual", "giant sword", "warm jacket", "wizards hat", "red bow and arrow", "red spear", "green potion", "heavy armour", "cursed axe", "gold ring", "purple ring"}; public Form1() { InitializeComponent(); SetUp(); } private void KeyIsDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { goLeft = true; } if (e.KeyCode == Keys.Right) { goRight = true; } if (e.KeyCode == Keys.Up) { goUp = true; } if (e.KeyCode == Keys.Down) { goDown = true; } } private void KeyIsUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { goLeft = false; } if (e.KeyCode == Keys.Right) { goRight = false; } if (e.KeyCode == Keys.Up) { goUp = false; } if (e.KeyCode == Keys.Down) { goDown = false; } } private void FormPaintEvent(object sender, PaintEventArgs e) { Graphics Canvas = e.Graphics; if (items_list != null) { foreach (Items item in items_list) { Canvas.DrawImage(item.item_image, item.positionX, item.positionY, item.width, item.height); } } Canvas.DrawImage(player, playerX, playerY, playerWidth, playerHeight); } private void TimerEvent(object sender, EventArgs e) { CheckCollision(); if (timeCounter > 1) { timeCounter--; } else { MakeItems(); } if (goLeft && playerX > 0) { playerX -= playerSpeed; AnimatePlayer(4, 7); } else if (goRight && playerX + playerWidth < this.ClientSize.Width) { playerX += playerSpeed; AnimatePlayer(8, 11); } else if (goUp && playerY > 0) { playerY -= playerSpeed; AnimatePlayer(12, 15); } else if (goDown && playerY + playerHeight < this.ClientSize.Height) { playerY += playerSpeed; AnimatePlayer(0, 3); } else { AnimatePlayer(0, 0); } this.Invalidate(); lblMovement.Text = "Movements: " + steps; } private void SetUp() { this.BackgroundImage = Image.FromFile("bg.jpg"); this.BackgroundImageLayout = ImageLayout.Stretch; this.DoubleBuffered = true; // load the player files to the list playerMovements = Directory.GetFiles("player", "*.png").ToList(); player = Image.FromFile(playerMovements[0]); item_locations = Directory.GetFiles("items", "*.png").ToList(); } private void AnimatePlayer(int start, int end) { slowDownFrameRate += 1; if (slowDownFrameRate == 4) { steps++; slowDownFrameRate = 0; } if (steps > end || steps < start) { steps = start; } player = Image.FromFile(playerMovements[steps]); } private void MakeItems() { int i = rand.Next(0, item_locations.Count); Items newItem = new Items(); newItem.item_image = Image.FromFile(item_locations[i]); newItem.name = itemNames[i]; timeCounter = spawnTimeLimit; items_list.Add(newItem); } private void CheckCollision() { foreach (Items item in items_list.ToList()) { item.CheckLifeTime(); if (item.expired) { item.item_image = null; items_list.Remove(item); } bool collision = DetectCollision(playerX, playerY, player.Width, player.Height, item.positionX, item.positionY, item.width, item.height); if (collision) { lblCollected.Text = "Collected the: " + item.name; item.item_image = null; items_list.Remove(item); } } } private bool DetectCollision(int object1X, int object1Y, int object1Width, int object1Height, int object2X, int object2Y, int object2Width, int object2Height) { if (object1X + object1Width <= object2X || object1X >= object2X + object2Width || object1Y + object1Height <= object2Y || object1Y >= object2Y + object2Height) { return false; // no collision } else { return true; // found collision } } } }