Collision Detection - How to Make a 2D Game in Java #6

RyiSnow
1 Nov 202126:43

Summary

TLDRIn this tutorial, RyiSnow demonstrates how to implement collision detection in a game development project. The video guides through setting solid tiles in the TileManager, adjusting player collision areas using a Rectangle class, and creating a CollisionChecker class to prevent the player from walking through obstacles. RyiSnow also discusses the importance of precise collision settings for better game mechanics and player movement control, concluding with a preview of upcoming features like object creation and interaction.

Takeaways

  • ๐ŸŒ The video is a tutorial on implementing collision detection in a game world map.
  • ๐Ÿ› ๏ธ The 'Tile' class has a 'collision' boolean that is used to define solid tiles like walls and water.
  • ๐ŸŽฎ Player movement is restricted by setting the collision property to 'true' for solid tiles to prevent walking through them.
  • ๐Ÿ“ Collision settings are applied to the player character by defining a 'solidArea' within the player's tile.
  • ๐Ÿ” The 'Rectangle' class is used to create a collision area for the player character with specified x, y, width, and height.
  • ๐Ÿ‘พ The 'solidArea' is made smaller than the player's tile to allow for better movement and control in the game.
  • ๐Ÿšซ Collision detection prevents the player from moving into a solid tile, enhancing game realism and mechanics.
  • ๐Ÿ”„ A 'CollisionChecker' class is created to handle collision checks for the player, monsters, and NPCs.
  • ๐Ÿ“š The 'GamePanel' class is used to instantiate the 'CollisionChecker' and integrate it with the game's update method.
  • ๐Ÿงฉ By calculating the player's 'worldX' and 'worldY' based on the 'solidArea', the game checks for collisions in four directions.
  • ๐Ÿ›‘ The tutorial concludes with the successful implementation of collision detection, with plans to create and display game objects in the next video.

Q & A

  • What is the main topic of the video?

    -The main topic of the video is implementing collision detection in a game development program to prevent the player from walking through solid objects like trees and water.

  • What is the purpose of the 'collision' boolean in the Tile class?

    -The 'collision' boolean in the Tile class is used to designate whether a tile is solid or not, thus preventing the player from walking through it.

  • Why is it important to set only specific parts of the player character as solid?

    -Setting only specific parts of the player character as solid helps to avoid issues like getting stuck on walls and improves the control mechanics, allowing for more precise movement through narrow paths.

  • What is the Rectangle class used for in the context of collision detection?

    -The Rectangle class is used to create an invisible or abstract rectangle that defines the solid area of the player character for collision detection purposes.

  • What is the default value of the 'collisionOn' boolean?

    -The default value of the 'collisionOn' boolean is false, meaning that by default, tiles are not considered solid for collision detection.

  • How does the video script suggest determining the solid area for the player character?

    -The script suggests using the Rectangle class to define a specific area of the player character as solid, adjusting the x, y, width, and height parameters to fit the desired solid area.

  • What is the CollisionChecker class responsible for?

    -The CollisionChecker class is responsible for checking collisions between entities, such as the player, monsters, and NPCs, and the game world's tiles.

  • Why is it necessary to check the worldX and worldY of the player's solidArea for collision detection?

    -The worldX and worldY of the player's solidArea need to be checked because collision detection must be based on the coordinates of the solid part of the player character, not the player's overall position.

  • How does the script handle checking collisions in different directions?

    -The script uses a switch statement to handle different directions, calculating the predicted position of the player after movement and checking the tiles that the player's solidArea would collide with in that direction.

  • What is the next step mentioned in the video script after implementing collision detection?

    -The next step mentioned in the video script is to create objects and display them on the screen for the player to interact with, such as picking them up.

Outlines

00:00

๐ŸŒณ Implementing Collision Detection

In this segment, RyiSnow discusses the process of adding collision detection to a game world. Initially, the player could walk through trees and waters, but now RyiSnow will modify the Tile class to include a collision boolean. This boolean is set to 'true' for solid tiles like walls and water, preventing the player from passing through. The default for non-solid tiles, like grass, is 'false'. RyiSnow also emphasizes the importance of defining the player's solid area to avoid issues with movement and control mechanics, suggesting that not the entire player tile should be solid, but only a specific part, which is done using the Rectangle class to create a solidArea.

05:11

๐Ÿ“ Setting Player Collision Area

This paragraph describes how to set the player's collision area within the game. RyiSnow explains that the player's solid area can be defined by creating a smaller rectangle within the player's tile, which is done by adjusting the x, y, width, and height parameters. The goal is to make the player's solid area more precise, allowing for better control and movement through narrow paths. RyiSnow provides an example of setting these parameters and suggests that developers can adjust these values to suit their game's needs.

10:16

๐Ÿ” Creating a Collision Checker Class

RyiSnow introduces the creation of a CollisionChecker class to handle collision detection for the player, as well as for other entities like monsters and NPCs. The class is instantiated within the GamePanel and is used in the Player class's update method to check for collisions. The CollisionChecker receives an Entity and checks if the player's solidArea is hitting a solid tile by calculating the worldX and worldY coordinates of the solidArea and determining the corresponding column and row numbers in the game's tile grid.

15:16

โฌ†๏ธ Collision Detection for the 'Up' Direction

In this part, RyiSnow focuses on the collision detection logic for when the player moves 'up'. The player's future position is predicted by subtracting the player's speed from the solidArea's worldY coordinate. The script then calculates the row number and checks two tiles in the 'up' direction for collisions. If either of the tiles is solid, the player's movement is blocked. RyiSnow also mentions the need to make certain variables public for the collision detection to function correctly.

20:21

โ†•๏ธ๏ธ Expanding Collision Detection to Other Directions

Having established the collision detection for the 'up' direction, RyiSnow proceeds to extend this logic to the other directions: 'down', 'left', and 'right'. The script involves adjusting the row and column checks based on the player's intended movement direction. For 'down', the bottom row is checked; for 'left', the left column; and for 'right', the right column. The process involves checking the tiles at the player's predicted new position and ensuring that the movement is allowed only if no solid tiles are encountered.

25:40

๐ŸŽฎ Finalizing Collision Detection and Previewing Future Steps

In the final paragraph, RyiSnow tests the collision detection system, confirming that the player character is now stopped by solid tiles like trees and waters. The script demonstrates that the collision detection works in all directions, enhancing the game's realism and playability. RyiSnow concludes by mentioning the next steps, which involve creating objects in the game that the player can interact with, such as picking them up.

Mindmap

Keywords

๐Ÿ’กCollision Detection

Collision detection is a fundamental concept in video game development that involves determining whether two objects have intersected with each other, which is crucial for realistic gameplay. In the video, collision detection is implemented to prevent the player from walking through solid objects like trees and water. The script describes setting up collision detection by marking certain tiles as solid and then checking if the player's movement intersects with these solid tiles, thereby preventing movement into those areas.

๐Ÿ’กTile Class

A 'Tile Class' in game development refers to a programming construct that represents individual units of a game's map or world, often used for defining terrain, obstacles, and other environmental elements. In the context of the video, the Tile class includes a 'collision' boolean property that determines whether a tile is solid or passable. The video script mentions setting this property to 'true' for tiles like walls and water to make them impassable.

๐Ÿ’กTileManager

The 'TileManager' is a component in the video's game engine that handles the organization and management of tiles within the game world. It is responsible for defining which tiles are solid and which are not, as well as other tile properties. The script describes how to use the TileManager to set specific tiles, like walls and water, as solid by adjusting their collision properties.

๐Ÿ’กSolid Tile

A 'Solid Tile' is a term used in game design to describe a tile that the player or other entities cannot pass through. It represents an obstacle in the game world. The video script discusses identifying and marking certain tiles, such as walls and water, as solid to implement collision detection, ensuring that the player character cannot walk through them.

๐Ÿ’กPlayer Character

The 'Player Character' is the avatar or representation of the player within the game world. It is the entity controlled by the player and interacts with the game environment. In the video, the script discusses how to set specific areas of the player character as solid to prevent them from passing through obstacles, which is essential for implementing collision detection.

๐Ÿ’กRectangle Class

The 'Rectangle Class' is a programming class used to create and manipulate rectangles, often used in game development for defining areas or boundaries. In the video, the Rectangle class is used to define the solid area of the player character, which is then used to check for collisions with the game's environment. This allows for more precise collision detection than simply considering the entire player tile as solid.

๐Ÿ’กCollisionOn

'CollisionOn' is a boolean variable used in the game's collision detection system to indicate whether a collision has been detected. In the video script, a 'collisionOn' variable is created and set to false by default. It is then checked during the collision detection process, and if a collision is detected, this variable can be set to true to prevent the player from moving in that direction.

๐Ÿ’กGamePanel

The 'GamePanel' is a component of the game's user interface that typically handles rendering and updating the game's visual elements. In the video, the GamePanel is used to instantiate the CollisionChecker class, which is responsible for checking collisions between the player and the game environment. This is an important step in integrating collision detection into the game's main logic.

๐Ÿ’กEntity

An 'Entity' in game development refers to any object or character within the game world that can be manipulated or interacted with. In the video, the script mentions creating a CollisionChecker class that checks for collisions not only with the player but also with other entities like monsters and NPCs. This highlights the generality of the collision detection system being implemented.

๐Ÿ’กUpdate Method

The 'Update Method' is a function in game programming that is called repeatedly to update the game's state, handle user input, and perform other tasks necessary for the game's real-time operation. In the video, the script describes placing collision checks within the Player class's update method, ensuring that collision detection is performed continuously as the game runs.

๐Ÿ’กSwitch Statement

A 'Switch Statement' is a control flow statement used in programming to perform different actions based on the value of a variable. In the video script, a switch statement is used to handle different player directions (up, down, left, right) for collision detection. This allows the game to check the appropriate tiles based on the direction the player is attempting to move.

Highlights

Introduction to implementing collision detection in a game development tutorial.

Utilization of the 'collision' boolean in the Tile class to prevent player movement through solid objects.

Setting specific tiles as solid by modifying the TileManager to enhance gameplay realism.

Explanation of the default 'false' collision setting for non-solid tiles.

The importance of defining solid areas within the player character for better control mechanics.

Demonstration of how setting the entire player tile as solid can restrict movement unnecessarily.

Discussion on the challenges of navigating narrow paths with solid collision settings.

Introduction of the Rectangle class to define solid areas within the player character.

Customization of the player's solid area to allow for more precise movement and control.

Instantiation of the solidArea rectangle with specific parameters to fit the player character's design.

Creation of the CollisionChecker class to manage collision detection for various entities in the game.

Integration of the CollisionChecker class within the GamePanel for broader collision detection.

Implementation of collision checks within the Player class's update method.

Calculation of the player's solidArea world coordinates for accurate collision detection.

Use of switch statements to handle different player directions and corresponding collision checks.

Detailed explanation of the 'up' direction collision detection process.

Adjustment of player movement code to account for collision results before allowing movement.

Expansion of collision detection to include other directions: down, left, and right.

Final demonstration of the game's improved collision detection in action.

Teaser for the next tutorial segment focusing on creating and displaying game objects.

Transcripts

play00:00

Hi guys, this is RyiSnow

play00:02

so last time, we loaded our world map

play00:05

and implemented a camera function

play00:08

so now we can move around the world, like this

play00:12

but still, we can walk through these trees and waters

play00:17

so in this video, we will implement collision detection in our program

play00:23

so the player won't be able to walk through solid tiles

play00:29

when we created this Tile class, we created this collision boolean

play00:35

so it's time to use this

play00:38

first, we go to this TileManager

play00:42

and look for a tile that we want to change it to a solid tile

play00:48

for example, this wall tile should be solid

play00:53

we don't want our player character walk through this tile

play01:01

we call this collision boolean and set it "true"

play01:12

also this water tile... this one too

play01:22

and this one too

play01:31

and if it's not a solid tile... like this grass tile

play01:36

then you don't need to add anything because the collision is false as default

play01:44

so you only need to add this if the tile is solid

play01:51

ok so tiles' collision setting is done

play01:54

then we decide which part of the player character is solid and which part is not

play02:03

the easiest way is setting the whole tile is solid

play02:07

but sometimes it won't produce the best result

play02:12

for example, if the whole player tile is soid,

play02:17

then he hits this wall at this point and cannot move further

play02:24

but maybe you want to move him a bit further... like this

play02:33

also, there's another issue

play02:36

if everything is solid, it's really difficult to get through a narrow path like this

play02:44

because even if the player is 1 pixel to the left, collision still happens here

play02:55

so you need to place him very precisely, like this

play03:01

and that is simply pretty stressful

play03:04

and bad control mechanics in my opinion

play03:09

for example, "oh i'm hitting this tile so let's move to the right little bit"

play03:15

and "oh now i'm hitting this tile and still i cannot go further"

play03:21

so to avoid this kind of hassle,

play03:24

we set a specific area of the character as solid, not everything

play03:31

like, only this part is solid

play03:36

then the player can get through this kind of narrow path

play03:40

and to set this kind of collision area,

play03:44

first, open this Entity

play03:53

we use this Rectangle class

play03:59

and i'm gonna name this solidArea

play04:08

with this class, we can create an invisible or abstract rectangle

play04:15

and we can store data such as x, y, width, and height

play04:20

also, we create a boolean called collisionOn, and the default is false

play04:32

now go to this Player class

play04:36

and instantiate that rectangle

play04:55

wait, oh what is this... soidArea... sorry

play05:11

and when we instantiate this rectangle, we can pass 4 parameters to the constructor

play05:23

for example, if you want to create a rectangle which is the same size as our tiles,

play05:30

you type like this:

play05:32

x = 0, y = 0, widht = 48, and height = 48

play05:39

or you can also type like this: gp.tileSize

play05:46

either way is fine

play05:48

or we can also leave this blank and set these values one by one

play06:23

either way is fine

play06:25

and since we want to make this rectangle a bit smaller than the player character

play06:31

we change these values a little bit

play06:36

maybe something like this

play06:38

so this gray area is not solid, and this area is solid

play06:43

so this slid area starts from x 8

play06:50

and width is 32

play06:54

and height is also 32

play06:58

so the top left corner is x = 8, and y = 16

play07:05

so in that case, we're gonna change this x to 8, and y to 16

play07:14

and widht is 32 and height is also 32

play07:22

you can adjust these numbers and find what works best for your game

play07:28

so we got this collision area for the player character

play07:32

now let's create a class to check collision

play07:36

inside this main package, create a class

play07:41

and i'm gonna name this CollisionChecker or whatever name you want

play07:52

and first, constructor

play08:00

and we receive GamePanel

play08:17

and create a method

play08:28

and we receive Entity here

play08:40

not Player but Entity

play08:43

because we will use this method to check not only player collision but also monster and NPC collisions as well

play08:56

now go to the GamePanel

play08:59

and instantiate this CollisionChecker class

play09:19

and pass this GamePanel

play09:24

and now go to this Player class

play09:26

and we check collision inside of this update method

play09:35

after this direction if statement,

play09:40

first, we set this collisionOn to false

play09:50

then call this...

play10:00

oh sorry

play10:03

this needs to be "public"

play10:08

so we're gonna call this checkTile method from here

play10:15

and pass this Player class as Entity

play10:19

since this Player class is a subclass of this Entity class

play10:23

so the CollisionChecker can receive the Player class as Entity

play10:29

alright, now the main part of this video

play10:33

so what we need to do is, to check if the player is hitting a solid tile or not

play10:43

to do that, first, we want to know the worldX and the worldY of the player's solidArea

play10:51

not the player's worldX and Y because collision needs to be detected based on these solidArea coordinates

play11:01

there are 4 points to be checked

play11:17

and we can find out these 4 numbers like this:

play12:52

then based on these coordinates, we will find out their column and row numbers

play13:15

we simply divide it by tileSize

play14:31

and finally we will create two more integers

play14:46

because basically, we only need to check two tiles for each direction

play14:54

if the player is going up,

play14:56

we only need to check what tiles, so the player's left shoulder and right shoulder are hitting

play15:05

so in this case, if the player is going up like this

play15:09

this is hitting maybe this wall tile

play15:12

and this right shoulder is hitting this grass tile

play15:16

so now we're gonna create a switch statement

play15:25

we're gonna check the entity's direction

play15:59

so let's take care of this "up" first

play16:32

for example, the player is here right now

play16:35

and he is trying to go up

play16:39

what we are doing here is, we kind of predict where the player will be after he moved

play16:59

so we subtract this player's speed from the player's worldY

play17:05

or the player's solidArea's worldY, to be precise

play17:10

now we know this row number so we can find out what tile the player is trying to step in

play17:20

and there are possibly two tiles

play17:35

so we're gonna call this mapTileNum

play17:38

this stores all the map tile information

play18:03

oh this also needs to be "public"

play18:13

and the other one is...

play18:27

we checked this point, this is tile1

play18:30

now we want to check this point, the right side

play18:51

with this information, we create an if statement

play18:56

and call this Tile array... this also needs to be "public"

play19:14

we're gonna use this tileNum1 as an index

play19:19

and check if this tile is solid or not

play19:44

if one of them or both are true, the player is hitting a solid tile

play19:51

so he cannot move this direction

play20:20

so if these collisions are false, then we don't do anything

play20:27

ok so this "up" case is done

play20:30

let's go back to this Player class

play21:36

and now we're gonna move these player movement lines from here to here

play22:02

maybe i like this format better...

play22:28

yeah because now we're checking collision so the player can move only when the tiles are not solid

play22:37

so first we only check the direction

play22:41

and based on this direction, we check collision

play22:47

and if collision is not happening, then we let the player move

play22:55

ok let's check this

play23:03

so now this tree tile is stopping the player character

play23:12

but it's still only the up direction

play23:15

you can still go left, down, and right

play23:19

so let's take care of the other directions too

play23:25

i think we can copy and paste

play23:33

we only change some variables

play23:39

so if the player is going down, we're not gonna check the top row but the bottom row

play23:51

so change this to bottomRow

play24:18

we're gonna change this from top to bottom

play24:28

and if the player is going left then...

play24:31

we're gonna check the left col

play24:39

and the left col will be...

play24:53

so now we're gonna check this point and this point

play25:12

if going right then...

play25:40

that's it, i think

play25:45

ok let's check this

play25:53

ok hitting the tile

play26:02

and this water tile too

play26:05

so collision is happening

play26:09

yup, looks good

play26:15

so this is getting more and more like a game

play26:18

so we took care of the collision detection

play26:21

next time, we will create objects and display them on the screen

play26:27

so the player can pick them up

play26:30

thanks for watching, and until next time

Rate This
โ˜…
โ˜…
โ˜…
โ˜…
โ˜…

5.0 / 5 (0 votes)

Related Tags
Game DevelopmentCollision DetectionPlayer MovementTile ManagementSolid TilesCamera FunctionWorld MapProgramming TutorialGame MechanicsVideo ScriptSolid Collision