Jump to content
  • Advertisement
  • entries
    36
  • comments
    11
  • views
    3056

About this blog

An update blog for projects going on that have some degree of interest

Entries in this blog

Algorithm Flexible Room Layout algorithm

While making a roguelike game, procedural generation have to be quick and yet intriguing enough for the generated level to be fun to just pick up and play. There are many ways to generate and laying out procedurally generated rooms. In The Binding Of Isaac, for example, you have many different types of regular room presets.  The generator just picks a preset based on things like room placement and size. Because those rooms are always of fixed size, this is a nice compromise. By having handmade presets the generated level is somewhat believable (i.e. there are no gaps or obstacles below a room door or secret room and whatnot).      Another example would be Nuclear Throne.  The game takes a different approach to procedural generation by keeping it relatively simple. Because it's not room-based like The Binding Of Isaac, there are more things like caves and large open area.  The gameplay also plays into this, as the player needs to eliminate every enemy to spawn a portal to the next level.      Because my game is somehow more inspired by The Binding of Isaac, the right way to procedurally generate rooms would be to use presets, and this is how I make special rooms. However, there's a big difference between The Binding Of Isaac and my game: my regular rooms aren't always the same size. This means that rather than having presets of regular rooms as well as special rooms I need something more flexible and, most importantly, dynamic.. The anatomy of a Room In my game, as I've said in a previous post, levels are big two-dimensional arrays from which the level geometry is generated. Every room of a level is made using a BSP tree. I won't go in details much on how rooms are generated, but in essence, we create a grid from which we trace a path between two rooms and sparsely attach bonus rooms along the way. Because I already have rooms sizes and whatnot with that level generation, I could reuse the same idea for room layouts. Within rooms, I've also set special anchor points from which props (or more precisely, prop formations, more on that later...) could be generated. Basic Layouts The idea here is to have room layout presets. Within those, presets are an array of prop formations, and each of these formations is linked to a specific anchor point. A formation has a two-dimensional boolean array that indicates whenever or not there should be a prop here. Let's take, for example, a diamond array: The dimension of the array depends on its rooms' dimensions. Here's how it's done: \( size = \left \lceil \frac{2(max(RoomSize_{x},RoomSize_{y}))) }{ 3 } \right \rceil\) In order to change the array's content we actually use common image manipulation algorithms... Bresenham's Line Algorithm The first used algorithm is the Bresenham's Line Algorithm.  Its purpose is to simply render a line describe by two bitmap points onto a raster image. To put it simply, we get the deviation (delta, or "d" for short) in both X and Y of each point of the described line and compare both of them. Depending on the biggest, we simply incremate the point on that axis and colour it in. Here's the implementation: public void TraceLine(Vector2Int p0, Vector2Int p1) { int dx = Mathf.Abs(p1.x - p0.x), sx = p0.x < p1.x ? 1 : -1; int dy = Mathf.Abs(p1.y - p0.y), sy = p0.y < p1.y ? 1 : -1; int err = (dx > dy ? dx : -dy) / 2, e2; while (true) { m_propArray[p0.x][p0.y] = true; if (p0.x == p1.x && p0.y == p1.y) { break; } e2 = err; if (e2 > -dx) { err -= dy; p0.x += sx; } if (e2 < dy) { err += dx; p0.y += sy; } } } Midpoint Circle Algorithm The midpoint circle algorithm is an algorithm used to render a circle onto an image. The idea is somehow similar to Bresenham's Line Algorithm, but rather than drawing a line we draw a circle. To do this we also need, for simplicity sakes, to divide the circle into 8 pieces, called octants. We can do this because circles are always symmetric. (It's also a nice way to unroll loops) Here's the implementation: private void TraceCircle(Vector2Int center, int r, AbstractPropFormation formation) { int d = (5 - r * 4) / 4; int x = 0; int y = r; do { // ensure index is in range before setting (depends on your image implementation) // in this case we check if the pixel location is within the bounds of the image before setting the pixel if (IsValidPoint(center + new Vector2Int(x,y)) { formation.m_propArray[center.x + x][center.y + y] = true; } if (IsValidPoint(center + new Vector2Int(x,-y)) { formation.m_propArray[center.x + x][center.y - y] = true; } if (IsValidPoint(center + new Vector2Int(-x,y)) { formation.m_propArray[center.x - x][center.y + y] = true; } if (IsValidPoint(center + new Vector2Int(-x,-y)) { formation.m_propArray[center.x - x][center.y - y] = true; } if (IsValidPoint(center + new Vector2Int(y,x)) { formation.m_propArray[center.x + y][center.y + x] = true; } if (IsValidPoint(center + new Vector2Int(y,-x)) { formation.m_propArray[center.x + y][center.y - x] = true; } if (IsValidPoint(center + new Vector2Int(-y,x)) { formation.m_propArray[center.x - y][center.y + x] = true; } if (IsValidPoint(center + new Vector2Int(-y,-x)) { formation.m_propArray[center.x - y][center.y - x] = true; } if (d < 0) { d += 2 * x + 1; } else { d += 2 * (x - y) + 1; y--; } x++; } while (x <= y); } Flood Fill Algorithm This is quite a classic, but it's still useful nevertheless. The idea is to progressively fill a section of an image with a specific colour while  The implementation is using a coordinate queue rather than recursion for optimization sakes. We also try to fill the image using west-east orientation. Basically, we fill the westmost pixel first, eastmost second and finally go north-south. Here's the implementation: public void Fill(Vector2Int point) { Queue<Vector2Int> q = new Queue<Vector2Int>(); q.Enqueue(point); while (q.Count > 0) { Vector2Int currentPoint = q.Dequeue(); if (!m_propArray[currentPoint.x][currentPoint.y]) { Vector2Int westPoint = currentPoint, eastPoint = new Vector2Int(currentPoint.x + 1, currentPoint.y); while ((westPoint.x >= 0) && !m_propArray[westPoint.x][westPoint.y]) { m_propArray[westPoint.x][westPoint.y] = true; if ((westPoint.y > 0) && !m_propArray[westPoint.x][westPoint.y - 1]) { q.Enqueue(new Vector2Int(westPoint.x, westPoint.y - 1)); } if ((westPoint.y < m_propArray[westPoint.x].Length - 1) && !m_propArray[westPoint.x][westPoint.y + 1]) { q.Enqueue(new Vector2Int(westPoint.x, westPoint.y + 1)); } westPoint.x--; } while ((eastPoint.x <= m_propArray.Length - 1) && !m_propArray[eastPoint.x][eastPoint.y]) { m_propArray[eastPoint.x][eastPoint.y] = true; if ((eastPoint.y > 0) && !m_propArray[eastPoint.x][eastPoint.y - 1]) { q.Enqueue(new Vector2Int(eastPoint.x, eastPoint.y - 1)); } if ((eastPoint.y < m_propArray[eastPoint.x].Length - 1) && !m_propArray[eastPoint.x][eastPoint.y + 1]) { q.Enqueue(new Vector2Int(eastPoint.x, eastPoint.y + 1)); } eastPoint.x++; } } } } Formation Shapes Each formation also has a specific shape. These shapes simply define the content of the formation array. We can build these shapes using the previously mentioned algorithms. There are 9 different types of shapes as of now. Vertical line A simple vertical line of a width of one Horizontal line A simple horizontal line of a width of one Diamond A rather nice diamond shape, especially pretty in corners Circle The circle is rendered using the Midpoint circle algorithm. Especially pretty in the center of rooms Cross A simple cross shape, i.e a vertical and horizontal line align at the center.  X Shape An "X" shaped cross, i.e two perpendicular diagonal lines align at the center. Triangle An Isocele triangle. Square A solid block. Every cell of the formation is essentially true. Checkers A nice variation of the square shape. Every other cell is false. There might be more types of shapes as time goes by, but it's about it for now. Placing props Once the array is set, we simply need to place the actual props in the room. Each formation is of an actual type, i.e. rocks, ferns, etc.  (For simplicity sakes, let's say that every prop is a 1x1x1m cube. This would simplify future steps.) In order to find their position, we simply align the array's center to the formations' specified anchor point. For each prop formation, we then instantiate props for each true cells while checking whenever or not the prop would be outside its room. Afterwards, we do a precise position check to make sure no props are either partially or fully outside a room. Finally, we make sure every room connections aren't obstructed with props. And voilà, we have a nicely decorated room In Game Screenshots Here's a couple of screenshots of what it looks like in-game  

jb-dev

jb-dev

Unity Weekly Update #16 - 【Relaxation】

Last week, there was a lot of thinking going on... There's still is least one new room plus many different refactoring. The Spa Firstly, there's a new room: the spa. This is a relaxing and zen room filled with classical Vaporwave aesthetics.     I've based it on really generic Vaporwave images around the internet.      The gist is that the player can cure its status effect by interacting with either massage table in the back. You may or may not have seen the fountain in the middle of the room. Its water is purely refractive with a solid, almost emissive colour when perpendicularly facing its surface (like some kind of Fresnel). This shader is part of Unity's Standard Asset, so it wasn't a hassle to get it up and running. The water is also being used in the restroom's toilet. There might be other places where it might pop up in future rooms. Minor Changes I've modelled and imported a generic spherical light that makes lighting a tad more tangible and credible.
Most lights are now coloured using blackbody colour temperatures, adding a little bit more reality to most rooms. Changed the palette texture. Colours are now more distinct from each other and more contrasting for at least the default palette. This is due to some feedback saying that the palette was too much pink... Changed how most solid colours meshes are being rendered so that they rely more on the palette texture. This means that changing the current sub-pallette or even the texture itself will dynamically change the colour of those meshes as well. Made the palette initializing run within the Unity Editor. Now there's no need to run the game only to look how models are shown. This really speeds up room designs and model previews, mainly because I previously needed to compile the game and regenerate the levels until the wanted room was generated. Refactored the RNG. Now each level has its own isolated RNG state.  This means that actions taken in one level won't influence the next one anymore. This also means that a given seed at a given chance (or luck if you fancy) stat will always produce the same level with the same loot. There's still some tweaking to do, but overall the isolated RNG system is in place. Many bugs were corrected, particularly with shaders. Next Week Most significant rooms are now in the game. There are still some minor rooms left, but these can wait: those might not even make it into the game so my energy could be better used on more critical stuff. Right now, normal rooms are in dire need of polish. Like in The Binding of Isaac, there will be different types of regular rooms. Each room would have different types of decoration in them. For example, some might have loads of rocks while others won't. There are currently only two placeholders kind of regular room... I do not know how many kinds of disposition there'll be: all of this needs research, sketches and design... There's a lot of work ahead. The good news is that heavy modelling is momentarily stopped. The following week will be fundamentally a coding one...

jb-dev

jb-dev

Unity Weekly update #15 - 【Enlightened】

Like last week, the room development is still in progress. While there are two new rooms I've also had time to tweak the lighting a bit here and there. New Lights Basically, I've tried to change the lighting of most rooms. First thing first, In order to properly shade the inside rooms I've used invisible shadow casters. At the time, it was the cheapest and quickest way to deal with it when I've started.  I did find out that another quick way to do this was with layers and light culling masks. Basically, every game objects that are inside sealed rooms is given a specific layer. That layer, in particular, was made to ignore the global directional light altogether. This means that there were no more need of these shadow casters (except on some opened rooms like the temple; the directional light can actually illuminate the room if the angle is good enough) I've also tried to fix the lighting in most rooms. Although not completely finished, it is getting prettier: The VIRTUAL Clinical Research Center As one of the newest rooms, this one represents a fictional clinical research facility named VIRTUAL Clinical Research. While in this room, the player can actually take part in a dodgy clinical trial involving either a strange cream, pills of unknown content and glowing fluids inside syringes. Each test takes away part of the player's health in exchange for cold hard cash. The ratio of health and cash is actually one to one as of yet. Taking the cream gives 5% of damage, the pills are 10% and the syringes are 25%. This room is quite useful if you're in dire need of cash, just like in real life. (except you don't get hurt as often in real life...) The Restroom This room is quite special. It a rather small room that is actually a normal public restroom, complete with a toilet, a sink, a real-time working mirror, a hand dryer, etc.  Although not functional right now, the idea is that the player can flush down one of its piece of equipment down the drain. You can only flush one piece of equipment per restroom because, well, toilets aren't really made to be able to flush down metal armours really... For those who don't know, a piece of equipment acts like a relic but is actually set to a specific equipment slot. You can only have one piece of equipment of a specific slot (for example, the player can have only one pair of gloves because it would be overpowered otherwise).  Like most RPG, different pieces of equipment have different types of stats bonuses. Each piece of equipment also has a focus alignment. This means that while the player is wearing those, its focus will progressively be drawn to whatever alignment the equipped piece is. There will also be additional stats bonuses that are applied if the player's focus matches a worn piece of equipment. But anyways, the reason the restroom isn't functional is quite simple: there's no piece of equipment yet. So it's something I'll have to get back to once there's at least one piece of equipment in the game... Next week The game is progressively coming together. Especially when it comes to rooms. There's still a lot of relics and capacities to add. There are also some rooms to add an maybe add different types of enemies and whatnot. I still want to work on rooms as of right now. The thing is that those rooms are really modelling heavy, and I really want to get those out of the way as soon as possible. The rest won't be as heavy as those, but once they're out of the way it will be a pretty big chunk of modelling that will be done. If there's time, maybe I'll work on capacities and relics...

jb-dev

jb-dev

Unity Weekly Update #14 - High Stakes

Last week was another modelling one, although there were some coding to be made in the last 2 days. Basically, I've continued the implementation of the pawnshop. Also, I had time to add a new room. The Pawnshop Although already functional, the pawnshop still needed some details props here and there. Here's a bunch of pictures showing the (almost) final version: As of now, the pawnshop's stock mainly consist of either prop from previously added rooms or even models of previous blender scene that went nowhere (take it as recycling I guess) I also want to point out that the cash register is modelled after classical mechanical cash registers like these ones:   There are also various guitars hanged on the back wall... Here's the actual reference I've used for the whole room: There's still the lighting to take care of... Also, keep in mind that I want to add more props from other rooms in the shop. So I still need to keep on moving along and get back to it when new props were added in the game. The Casino There's also a whole new room: the casino. This room acts like a giant slot machine for stats. Like traditional slots machines, the player simply pulls its lever to stop the currently active slot. There are 3 slots: one that states which stats the bonus applies, another one stating whenever it's actually positive or negative and finally the actual bonus amount. I won't lie: I kinda wanted to mimic Mario Party's mythical Chance Time. For those who aren't familiar, Chance Time was an event in the Mario Party games in which two players are forced to give/exchange specific items between each other. The player involved and the actual items are given by a slot machine-ish process. Here's a compilation of Chance Time events: As for the casino, I'm not quite sure whenever the player needs to buy in before the slots start spinning. What I'm sure of is that this process is only once per casino and that the bonus/malus is permanent. Also, the room is not fully decorated nor is lighted, but as of right now the main goal is to debug the actual slot mechanic. Next week Like before, next week is going to be room-centric again. There are also bugs with those slots that need to be fixed. They don't always line up correctly and sometimes even decides to give the player a completely different outcome.  Once most rooms are either fully or partially implemented, then maybe the next step would be to either fix animations or complete AIs. Afterwards, we still need capacities and relics... Some code refactoring wouldn't hurt either.

jb-dev

jb-dev

Music New music track released - VIRTUAL 洞窟

I've recently released on YouTube a new track part of the game's original soundtrack. I have yet to choose how this track is going to be used, but chances are that this track will be used in a cave-like level (mainly due to its title) If you got any type of feedback, don't be shy! I'm always willing to get better and am always open to criticism. 

jb-dev

jb-dev

Unity Weekly Updates #13 - Serenity

Last week was a modelling one. There aren't a whole lot of new mechanics but it was still a productive week nevertheless. Custom Font Firstly, I've previously talked about creating a custom font to display some of the GUI icons. Well, with the use of FontForge, we were able to add vectorial art in a TrueType font. For those who don't know, FontForge is an open source font-making app. It's pretty advance and can actually make good looking fonts. There's a pretty acute learning curve though. If you're using it on Windows, you'll need to fiddle around with the setting though. Otherwise, it can really run with a whole lot of hiccups and crashes. With FontForge, you can actually import vectorial graphics right into the font. Because I've already had SVG files of most of my used icons, it was just a matter of a couple of clicks and everything was imported. However, it wasn't a piece of cake: although imported, we still need to properly align those graphics up so they could be properly displayed. With FontForge you can export the custom font to different file formats. Thankfully, we can export in TrueType, which is exactly the type of font file Unity uses. Once the TrueType file is created, we can then use Unity's dynamic font rendering to display our GUI icons at any resolution we need without rescaling and rerendering any texture. However, there's a big drawback: fonts are always monochromatic. If we want a coloured icon then we'll have no other option besides using a traditional bitmap texture. (Colour fonts do exits... However, their support isn't really widespread) But anyway, here's how it looks: New rooms Secondly, there are also two new rooms. All of these rooms are linked to crystals.  Now that the player can know the number of crystals they currently have, those rooms can safely be integrated and tested without any hiccups. The Temple When visiting a temple, players can donate their crystals to gain back health points. To do this, the player simply needs to interact with the box at the back of the room while holding a crystal. Temples are modelled after Japanese Shinto temple/shrine. I've taken some liberties here and there but the overall theme is Japan. They are also much more open compared to other rooms. When the sun is right, the lighting can be quite charming. The Pawnshop The pawnshop isn't finished yet, but it's functional nevertheless. The player can exchange their crystals for a small amount of money by interacting with the yet-to-be-modelled cash register. Once finished, the pawnshop will have some fancy props here and there much like a typical pawnshop: things like guitars, jewellery and, of course, crystals. But for now, the room is kinda bland and boring... Minor updates There are also some new models and code refactors. For once, the diner now has a nice sign up on its roof: Aside from that, there aren't a whole lot of minor differences. Next week Like I've stated before, a lot of rooms can be added into the game now that most gameplay mechanics are coded.  And there's still a whole lot of rooms to implement. Of course, I still need to model out the pawnshop and add its details. There might be some polishing to do with many gameplay mechanics and maybe a refactor or two.  There's a lot of work ahead of me.

jb-dev

jb-dev

Unity Weekly Updates #12 - Having a 【Midnight Special】

Last week didn't have any particular theme, although it still was a busy one... Statuses First off, all statuses now have effect textures. these are really abstract, but nice to look at. (From left to right: Bleeding, Burning, Damned, Frenzied, Frozen, Knocked Out, Poisoned, Paralyzed and Stunned) Also, I've perfected statuses effects on enemies. Now their current status is a lot more obvious. A nice status icon is displayed over their head to help identify that status. The Diner Secondly, I've added a new room: the diner.  The idea of it is quite simple: the diner offers food for the player to eat.  The room itself is modelled after classic 50s diners with a jukebox and checkered patterns all over the place. There's even a nice neon sign that is truly aesthetic.  The lighting is still a WIP, but the models themselves are pretty much done. There might be some details to add here and there, though... The exterior also needs some work. I was thinking of giving it a huge diner sign, but for now, there's nothing fancy... Crystals Lastly, I've given the player the ability to switch their active crystals. For those who didn't know, crystals are run-persistent collectables that can give the player the opportunity to take shortcuts that gives fame and fortune to whoever chooses to take them. A GUI element is displayed at the bottom of the screen. Within it, there are 3 crystal counters for each type of crystals. When the player switches their active crystal, the element rotates around to display the right counter at the right time. There's even a nice animation for it. I've only worked on this yesterday, so it still has rough edges here and there. Also, there's no discernable way to identify the active type of crystal on the GUI element alone as of yet... There are some icons that could be ready, but I want to try to put those icons in a custom font file. This way, I can use Unity's dynamic text display functionality to have scalable graphics. One of the drawbacks of this is that only monochrome icons can be used... Minor updates Modified the bank so that it spawns with a back wall Fixed bugs with MonoBehaviours scripts presets Fixed a whole lot of bugs with the map generator. Turns out that when the player was extremely lucky, they could remain trapped in the stating room because all other rooms would become secret rooms. Added a limit on how many secrets tunnel rooms can be spawned Added a ceiling to most room obstacles such as locked doors and cracked walls so that the lighting won't look weird anymore. Added back walls to special rooms. Thus, the design of those rooms will be applied continuously rather than abruptly end. Changed the tri-colour decal shader to add emission (mainly used with the diner's neon sign) This week Now that the diner is done, I can go ahead and continue the implementation of even more rooms.  Last time I've talked about status-themed rooms, but turns out that there are a lot of other more important rooms to be added beforehand. I will be adding these up progressively... Now that the player knows their current active crystal type and their remaining amount, I can also add rooms dealing with those. I could also try to spawn pickable crystals, but right now rooms seem to be more important than crystals: they add more opportunities and varies the gameplay a lot. And finally, another possibility is to actually create these custom font files I've previously talked about, although it's not that important... Before I forget! Last week I've forgotten to mention that I've also tried to compose some music for the game. Here's a preview: ohok.mp4

jb-dev

jb-dev

Unity Weekly Updates #11 - Ms. Liza, I don't feel so good...

Last week I've worked on implementing statuses in the game. To put it simply, statuses negatively affect entities. Things like poisoning or bleeding, for example, will continuously dish out damage for a specific amount of time. Statuses Here's a list of some statuses and their effects. Keep in mind that statuses times aren't final and will eventually change depending on the impact of their effects...  Poisoned This status is self-explanatory. It will damage the entity for about 20 seconds. The damage amount will increase linearly through time.  Burning In essence, the entity is burning. Not dissimilar to being poisoned, the burning status also damages the entity for 20 seconds. The difference here is that the damage will increase using a reciprocal function.  Bleeding The entity is bleeding heavily. Again, that status is like the previous two. The difference here is that the damage will increase logarithmically.   Frozen The enemy is frozen solid. It can still move but at a reduced speed. Can also attack, but at a slower rate than usual. It will go away after 20 seconds.  Damned The enemy is cursed. For 20 seconds, the entity will be extremely unlucky.  Any luck tests will fail regardless of the entity's current luck.  Paralysed The entity is paralyzed. For 20 seconds, the entity can't move.  Frenzy The entity is caught up in a violent frenzy fits. If the entity isn't the player, then they will ignore the player and attack its friends.  If the entity is the player, then the situation is reversed: every entity will attack the player. It lasts for 20 seconds. After then, the fits end. Here's a video of frenzied enemies fighting themselves: InAFrenzy.mp4  Stunned The entity is blinded and incapacitated. A big and blinding flash is produced. The affected entity retrains their mobility, but both vision and earing are temporarily lost.  Knocked out The entity is knocked out. it can't move or see... A mix between paralyzed and stunned, except that everything will black out rather that light up. Statuses visual effects Each of these effects will have their own visuals to help to identify what type of effect is induced in who. If the effect is applied to the player, then a vignette effect is applied to the screen.  This effect actually has a nice wavy effect among other things... Here's a video of it: wavy.mp4 When inflicted by the frozen status, the player will also see ice crystals forming on their screen, just to be fancy.  If otherwise an AI is given a status, then the same pattern will be applied to it. The pattern is also screen aligned, making it really abstract. New Relics and Activated items Because statuses are now fully implemented in the game, there's now even more relics and activated items. These are directly related to statuses and give the player unique capacities like to those as well. Relics There are 4 new relics. These are all related to statuses in one way or another... Hot dreams This is an abstract representation of a sunset. It's actually quite cliché in 80s aesthetics... This relic also does billboarding. There are just some shapes that don't translate well in 3D... With this, the player is able to set entities on fire (thus giving the burning status) to attacked enemies. These attack can be direct (like a hit) or not (like a laser beam).  As long as it originated from the player, it's all right. Here are its modifiers: -5% ATK +5% AGL Ice drop This is an ancient artifact resembling a raindrop. While holding it, any attack received or given will result in the other party to receive the frozen status. Here are its modifiers: +10% DEF -5% ATK Crystal Cola This is a clear cola. It's supposed to represent a Crystal Pepsi. This relic gives the Purifier capacity. In essence, it can make the player resistant to status changes. Here are its modifiers: +10% LCK -5% ATK Crystal Tea A nice tea beverage. It's a reference to Arizona green tea. It has the Purifier capacity and also speeds up attacks. Here are its modifiers: -25% ATK +25% AGL Activated Items There's only one new activated item: the Lipstick. Lipstick Alignment: Future Funk This is a lipstick. A red one in fact. While holding it, the player will experience a small growth...  When activated, the item will make any hostile entities in a 25m radius receive the frenzy status. Here are its modifiers: -20% LCK Minor changes There weren't a whole lot of other changes. But the AI was considerably changed to include status effect in their behaviour (ex: stunned enemies can't spot the player or frenzied enemies will attack other enemies)... Next week There's still a lot of work on status effects. For example, not all statuses have patterns, and there's also more effects to be added and tweaked here an there. If there's anything new, it could be better props or even more specials rooms... After all, now that statuses are in, there's a lot of things that can be implemented.

jb-dev

jb-dev

Unity Weekly Updates #10 - yum ゝ彙ヶ

Last week I've worked on two things: Foods and Activated Items. I can safely say that my goal was achieved, and even surpassed. I've managed to add three working Activated Items and a whopping 9 foods in total. So let's dive right into it. Focus system crash course Before we dive right into activated items, we first have to know about the focus system. The focus system is like the classes or specializations system in most RPGs. Except that the focus system is actually quicker and is overall much more simpler than traditional RPG class system. (Because it's in a roguelike game and permadeath exists) In essence, each time the player uses those items, then its focus will shift through three poles: Vaporwave (Rogue/Assasins), Future Funk (Marksmen) and Hardvapor (Brawler). Having a certain focus can results in additional bonuses in certain stats, and can even give weapons and other items different type of bonuses and capacities. As of right now, no actual bonuses are implemented. This is because the focus system is primarily linked to the player's equipment... These aren't in the game just yet... Activated items If you played The Binding of Isaac, then you may be familiar with this concept. The idea is to have an item that can have an effect when manually triggered. Activated items work just like this: they are items that the player can activate. Most of the time, these give additional abilities to the player, like becoming temporarily invisible. Activated items can also have relic-like capacities that apply as long as the item is held, and can also have modifiers. Items can also have a focus alignment. Right now, only three of these are functional in the game. The Cellphone Alignment: Vaporwave This is an old piece of junk. It's supposed to represent an old Motorola brick phone. With this phone, the player is able to set up a one-way teleportation trip. First, the player needs to set up an exit point by activating it. This will create a weird sphere of spatial distortion Afterwards, when the player activates the item once more, they will be instantly teleported to it. Useful when you're in a huge level and want to get back to a specific room like a mall after getting more dosh. Here are it's modifiers: -5% ATK -10% HP Survival Gear Alignment:  Hardvapor This activated item is supposed to represent a survival backpack. With this item, the player can sacrifice its health for foods. Here are its modifiers: -20% AGL -10% HP This Alignment: None This is this or at least my interpretation of it. In my head, an object always was a big red specular sphere. Maybe it's because I started making games with Game Maker? Perhaps... With This, the player can reroll all items in a 25 meters radius for 10$. Here are the modifiers: +25% LCK -10% HP Foods Foods are like temporary relics. They sometimes have capacities like relics and also have modifiers that are usually out of this world. When the player eats foods then a countdown is initiated. When the countdown is finished, all modifier and capacities given to the player are removed. Right now every food lasts for about 5 seconds. This will be individually tweaked based on things like modifiers and capacities... Here's a list of foods in the game: Pineapple This is a simple pineapple. Nothing special here Here are the modifiers: -10% LCK +25% ATK +50% DEF -10 AGL  Banana A normal banana. Here are the modifiers: +75% LCK +68% DEF +50% AGL Lime A normal lime, cut in half. Here are the modifiers: +10% LCK +25% ATK +75% AGL -10% HP Pineaburger A burger made of a slice of pineapple. There's also a lettuce leave thrown in there for good measure. Here are the modifiers: -10% LCK +25% ATK +50 % DEF -10% AGL Double Deluxe A plain waffle topped with whipped cream and glazed with some kind of syrup (claimed to be raspberry, but sure doesn't taste like it) Here are the modifiers: +75% LCK +10% ATK -25% DEF +10% AGL +5% HP Instant Ramen A normal instant ramen bowl. chopstick included. Here are the modifiers: +50% ATK +50% AGL -25% HP Bento box A somehow 80s bento box, with crazy shapes, lines and colours. Comes with chopsticks. Here are the modifiers: +25% LCK +10% DEF -10% AGL +75% HP Toast Sandwich A somehow plain looking sandwich. It appears to have a heavily buttered toast in the middle. This is one of the food that can give you a capacity. When eaten, it gives the capacity to do a double jump. Here are the modifiers: -10% LCK +25% DEF -50% AGL -5% HP Minor updates There are now proper debug tools, such as spawning folders and so, making the testing phase so much quicker Resolved some bugs with mall inventory not being properly chosen Finally added relic/foods/equipment/weapon spawning to folders items. This means that the player can finally get good loot from folders. Fixed an infrequent bug that gives wrong orientation to some rooms (i.e. some breakable wall used to spawn perpendicular to the rooms) Added a bunch of things to add effects like 2d drop shadows and outline rendering Next week Next week I planned to add statuses to the game. Statuses like poisoned of stunned. There's already a list of statues that was previously prepared. Now it's just a matter of implementing those. Otherwise, if I have the time I'm probably going to continue the implementations of items/capacities... I also realized that while testing things out I just forget I'm testing and I just play the game (even though there's only one unfinishable level) I genuinely had fun... I wish this feeling will get bigger as this is developed.

jb-dev

jb-dev

Unity Weekly Updates #9 - Relic Mania

In my previous update, I've said that the next step would be to integrate relics in the game. I'm proud to say that I've managed to implements some of the planned relics. What are Relics? If you played The Binding of Isaac, you may recall it's Passive Collectibles. Relics are the equivalent in this game. In other words, Relics are run-scoped upgrade the player either find or (if they're lucky) buys in malls. These give stats percentage bonus (i.e. +25% bonus in attack) and also give the player special capacities. What are Capacities? Capacities are passive (i.e. not explicit, or don't need special inputs) abilities the player gain. For example, one capacity could be the capacity to shoot laser beams at each attack. There's a science to it, though. They need considerable balance tweaks here and there just to make sure the game won't break with these capacities. Some capacities are linked to relics, and others not. For example, a capacity can be linked to a specific Item or even Foods. Right now, there are no items or Food in the game, so we'll talk about those in due time... Stats crash course Before we continue with the relics, we first need to understand stats. Stats are exactly what you think they are: just like in most RPG, they quantify the skills of a given entity. In the game, there are 5 base stats : Chance (or Luck if you're fancy): This stats dictates the probability of a player to have good things happen to them (e.x. good loots spawns after an enemy is killed or a lot of special rooms and tunnels are spawned).
It also dictates your chance of doing a critical hit (when so, the total damage output are 50% stronger) Attack: it's self-explanatory. This simply gives how much damage is given at each hit Defence: Also self-explanatory. This simply says how much damage is subtracted from an attack Agility: This stats dictates how fast your character goes. there might be more in the future, but for now, it only affects this Vitality (or Health if you're fancy): This stat simply represents your maximal health. These make CADAV. I don't know if it's clever enough, but it's catchy. (Not as good as SPECIAL, but good enough) For each stat, there is two different type of bonus/malus. These are a unitary bonus (or simply bonuses) and a percentage bonus (or modifiers). Bonuses usually come with pieces of equipment (things like armour and/or weapons), while modifiers are usually applied with capacities as a counterweight. Relics List Here's a small list of relics that are fully functional as of today: Laser Gem The laser gem is a relic resembling an abstract transparent cube with an opaque core. When the player picks up that relic, it gives them the ability to fire penetrating laser beams that deal damage to enemies when the player attacks. When the laser collides with anything but entities (like enemies) it will be reflected. This can be a quite powerful tool to quickly dispatch large amounts of enemies. The beam itself last for about 10 seconds, and only 3 beams can be fired at a time. Here are the modifiers: -10% of Attack +5% of Luck Modern Computing This relic is also abstract, but it's nevertheless more meaningful than the previous relic. Both its name and its model references something really vaporwave. But I'll let you figure it out. When the player grabs this relic, a combo system is activated: for every enemy killed, drops that cames from defeated enemies will linearly increase in number. Of course, being a combo system, if the player is hit then the combo is reset. Here are the modifiers: -5% of Luck -4% of Attack Credit Card The credit card is a credit card. (I didn't know what you expected) With this cool relic, the player can actually purchase anything they want anywhere even if they lack the money for it.  Buying an item without the needed money creates a debt in the player's funds. After each 10$ of debt, a random amount of negative modifiers are applied to the player's stats. When the player pays off their debts then these nerfs are progressively removed. Because of this special capacity, no base modifiers are applied when this relic is grabbed. DOUBLE-VISION This relic is rather abstract. It's actually a pair of eyes. When the player grabs this relic, every loot that are consumables (i.e bombs, keys or money) are doubled. Here are the modifiers: -5% of Attack -10% of Luck +5% of Agility Extension Cord This relic is simply a North American electric extension cord. There are two capacities attached to this relic. The first one simply makes the range of your attacks bigger. Its just actually the game resizing your weapons... Nothing special here. The second one is more a nerf than anything else: It slows down your attack speed by half. Here are the modifiers: -25% of Attack -25% of Agility Boxed Copy This relic is a Software box. It's supposed to mimic the Windows 9x boxes. With this relic, on the first successful hit by the player to an enemy, the latter has a chance to get "Boxed". When being "boxed", enemies are transformed into a similar box like the relic itself. However, that box is able to be opened by the player. It then spawns a random amount of consumables. It essentially one hit enemies if your lucky and gives you loot too. This only works on the first hit: subsequential hits won't work. Here are the modifiers: -25% of Attack Atk-booster 2000 This relic is a computer chip, presumably a CPU. It simply increases your attack speed by half. Here are the modifiers: -25% of Attack +10% of Agility Watch Out! This relic is a simple watch. With this one, you gain the ability to backstab other enemies. (not unlike the TF2 backstab) This means that if you hit their back they get one hit. In essence, this works by using the same algorithm that my vision field Here are the modifiers: -40% of Attack -25% of Health +5 of Agility Minor Updates Items that are in malls, along with relics and pieces of equipment, now rests on pedestals. These get removed when the item is picked up or otherwise get removed
There's now a key collectible that can spawn with any type of loot. Picking these up simply increments the player's total amount of keys
The Big Mall (the generic one) now has a chance to spawn a buyable relic in its inventory Fixed many bugs with a whole lot of things Thrown items now properly trigger AIs: they will look at the player that has thrown said projectiles rather than the projectile itself What's next? This week I'm planning to add more capacities and maybe add either Foods or Items in the game. Same goal as before: at least one Food or Item. Just to be clear: Items are like The Binding Of Isaac's Activated Collectibles except that they also change the player's stat and may also add passive capacities while the item is being held. As for food, think of relics, but temporary (a bit like Minecraft's potions). Here comes another big week I guess...

jb-dev

jb-dev

Unity Weekly Update #8 - Locked down

I've decided to change the frequency of these updates: most of the times, I just do some minor updates and graphical tweaks here and there. Therefore, if I do these updates weekly, then I'll have a lot more content to write about. So, yeah... Last week, I've been working on adding many different types of rooms in the level. You may or may not know that I use BPS trees to generate a level, and previously, only 5 types of rooms spawned in a level: starting rooms, ending rooms, normal rooms, tunnel rooms and Malls. It was very static and not flexible, so I've changed it to make it more dynamic. Malls Variations First, I've added two different variations for Malls: Blood Malls and Clothes Malls. These were originally planned and already built. Big Malls These are your typical type of Malls. You can find everything here. This is where, for example, you'll find hearts, keys and/or bombs. They were already in the game, but now they're more specialized (or generalized in this case) Blood Malls The Blood Malls specialized in bloody activities. (meaning that you'll mostly find a selection of weapons here) Clothes Malls The Clothes Malls are specialized in clothes, which in our case are actually pieces of equipment the player can have New Rooms Aside from these new type of malls, I've also added 3 new types of rooms. These rooms, however, are guarded by a locked door: the player must use a key to enter. In order to unlock a locked door, the player just needs to touch it. If the player has enough keys, then a key is used and the locked door disappears. There's also an event that triggers that can do things when the player unlocks the door (like revealing hidden models and what not) The Gym The gym is a room resembling some of these outside gyms you can see in some places.  The player can use up to tree gym equipment to get a permanent stats bonus to a randomly selected stat.  The prices of usages of these gym equipment doubles after each use. (i.e. if using one piece is 10$, then after buying it the others will cost 20$ and so on) I've planned that NPC would use non-interactive gym workstations for decoration, but it's not really important as of right now... The Bank The bank is not fully functional at the moment, but it still spawns. The idea is to give the player a way to store money persistently throughout runs. The player can then withdraw money (with a certain transaction fee) from that bank. That means that you can effectively get previously deposited money back when you'll need it the most. The Landfill The landfill gives you the opportunity to gain back previously thrown away pieces of equipment. Basically, the game stores the last three thrown away pieces of equipment. When the rooms spawn, it simply displays you those pieces of equipment. you can then pick them up for free. This, however, comes with a caveat: pieces of equipment that will be switched from a previously thrown away pieces of equipment won't reappear in another landfill. Also, once the landfill despawns, the items in that landfill will be discarded. (Think of it as a last chance opportunity) There aren't any props at the moment, but it's fully functional. Minor Tweaks Aside from that, there are also some minor tweaks: Bombs now damage the player if the latter is within its blast radius; Player jumps are now more precise: letting go of the jump button early makes a smaller jump than if it was held down longer; Ground detection (that was previously done with raycasting) now uses Unity's CharacterController.isGrounded property; When the player is hurt, a knockback is applied to him; The strength of said knockback is actually the total amount of damage the player took. Coins and money items now emit particles to help the player localize those important items;
They're now keys (left) and bombs (right) counters in the HUD;
The key one still needs a specific icon, but it's fully functional; There were many shader optimizations and adjustments: Many shaders were merged together and are now sharing most code; I've also changed the shaders so that we can use GPU instancing for most props, I also now use MaterialPropertyBlock for things like wetness; Also, now the palette texture and its palette index are now global variables, this effectively means that I only need to set these values once and everything else follows; A small "Sales" sign is placed in front of most types of malls. This sign has a random orientation and position each time it's spawned. ;
Props that obstruct a passage are removed from the room; This way no prop can obstruct the room so that the player cannot exit it. Some rooms now spawn ferns instead of palm trees;
Lianas also have different configurations based on which prop spawns. Next week Over the next week, I've planned to integrate the first relic. Relics are items that give the player capacities and stats boosts. It's common to have something similar in most roguelite and roguelike games. That type of thing needs to have a good abstraction in order to work: there are many different types of capacities that affect the player in radically different ways. There's a lot of work ahead. But I'm confident it'll be easy. Just need to get in the groove.

jb-dev

jb-dev

Unity Daily Update #7 - Another plane of being

During the past days, lots of shaders were updated and other visual things did too. Firstly, I've added lights effects when the crystals get shattered. There's also a burst of particle emanating from the broken crystal on impact. Also, enemies now leave a ragdoll corpse behind when they die. I love some of the poses those ragdolls make. On another note, I've toyed around with corpse removal and got captivated by the shrinking effect it created. It can sometimes be off-putting, but I'm still captivated. I've also added a nice VHS-like effect from layering two VHS shader together; namely "more AVdistortion" and "VHS pause effect". I've already ported the former and it's already active and the latter was just a matter of porting GLSL shaders to HLSL. No biggie. I did change the code a bit to make the white noises move through time. And there's nothing like trigonometry to help us with that fixed4 frag (v2f i) : SV_Target { fixed4 col = fixed4(0, 0, 0, 0); // get position to sample fixed2 samplePosition = i.vertex.xy / _ScreenParams.xy; float whiteNoise = 9999.0; // Jitter each line left and right samplePosition.x = samplePosition.x + (((rand(float2(_UnscaledTime, i.vertex.y))-0.5)/64.0) * _EffectStrength ); // Jitter the whole picture up and down samplePosition.y = samplePosition.y + (((rand(float2(_UnscaledTime, _UnscaledTime))-0.5)/32.0) * _EffectStrength ); // Slightly add color noise to each line col += (fixed4(-0.5, -0.5, -0.5 , -0.5)+fixed4(rand(float2(i.vertex.y,_UnscaledTime)),rand(float2(i.vertex.y,_UnscaledTime+1.0)),rand(float2(i.vertex.y,_UnscaledTime+2.0)),0))*0.1; // Either sample the texture, or just make the pixel white (to get the staticy-bit at the bottom) whiteNoise = rand(float2(floor(samplePosition.y*80.0),floor(samplePosition.x*50.0))+float2(_UnscaledTime,0)); float t = sin(_UnscaledTime / 2); if (whiteNoise > 11.5-30.0*(samplePosition.y + t) || whiteNoise < 1.5-5.0*(samplePosition.y + t) ) { // Sample the texture. col = lerp(tex2D(_MainTex ,samplePosition) , col + tex2D(_MainTex ,samplePosition), _EffectStrength); } else { // Use white. (I'm adding here so the color noise still applies) col = lerp(tex2D(_MainTex ,samplePosition), fixed4(1, 1, 1,1), _EffectStrength); } return col; } It's nice to have HLSL code, but a video is better:  

jb-dev

jb-dev

Unity Daily Update #6 - Dynamically colored decals

Today was kind of a slow day too. I've haven't got a lot of sleep lately (thanks little hamster wheel in my head) But at last, I was still able to add (and also fix) some graphical components here and there. In short, I've made the first and last rooms of the level more distinct from every other room. For example, I've added a room flow on these rooms to properly align props and, in the case of the starting room. the spawning rotation. I've also added a little decal-like plane that tells the player what to do (take it as a little tutorial, if you may) The important thing is that this decal is, not unlike my palette shader, dynamic in terms of colours. What I've done is quite simple: I've mapped each channel of a texture to a specific colour. Here's the original texture: After inputting this texture in my shader, it was just a matter of interpolating values and saturating them: Shader "Custom/TriColorMaps" { Properties { _MainTex ("Albedo (RGB)", 2D) = "white" {} _Glossiness ("Smoothness", Range(0,1)) = 0.5 _Metallic ("Metallic", Range(0,1)) = 0.0 _RedMappedColor ("Mapped color (Red channel)", Color) = (1, 0, 0, 1) _GreenMappedColor ("Mapped color (Green channel)", Color) = (0, 1, 0, 1) _BlueMappedColor ("Mapped color (Blue channel)", Color) = (0, 0, 1, 1) } SubShader { Tags { "RenderType"="Transparent" } LOD 200 CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types #pragma surface surf Standard fullforwardshadows vertex:vert decal:blend // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 sampler2D _MainTex; struct Input { float2 uv_MainTex; }; half _Glossiness; half _Metallic; fixed4 _RedMappedColor; fixed4 _GreenMappedColor; fixed4 _BlueMappedColor; void vert (inout appdata_full v) { v.vertex.y += v.normal.y * 0.0125; } // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing. // #pragma instancing_options assumeuniformscaling UNITY_INSTANCING_BUFFER_START(Props) // put more per-instance properties here UNITY_INSTANCING_BUFFER_END(Props) void surf (Input IN, inout SurfaceOutputStandard o) { // Albedo comes from a texture tinted by color fixed4 c = tex2D (_MainTex, IN.uv_MainTex); c.rgb = saturate((lerp(fixed4(0, 0, 0, 0), _RedMappedColor, c.r) + lerp(fixed4(0, 0, 0, 0), _GreenMappedColor, c.g) + lerp(fixed4(0, 0, 0, 0), _BlueMappedColor, c.b))).rgb; o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" } Also, note that I've changed the vertices of the model. I needed a way to eliminate the Z-Fighting and just thought of offsetting the vertices by their normals. In conclusion, It's nothing really special, really. But I'm still working hard on this. EDIT: After a little bit of searching, I've seen that you can give a Z-buffer offset in those Unity shaders by using the Offset state.  So I've then tried to change a bit my previous shader to use that functionality rather than just offsetting the vertices: SubShader { Tags { "RenderType"="Opaque" "Queue"="Geometry+1" "ForceNoShadowCasting"="True" } LOD 200 Offset -1, -1 CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types #pragma surface surf Lambert decal:blend // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 sampler2D _MainTex; struct Input { float2 uv_MainTex; }; fixed4 _RedMappedColor; fixed4 _GreenMappedColor; fixed4 _BlueMappedColor; // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing. // #pragma instancing_options assumeuniformscaling UNITY_INSTANCING_BUFFER_START(Props) // put more per-instance properties here UNITY_INSTANCING_BUFFER_END(Props) void surf (Input IN, inout SurfaceOutput o) { // Albedo comes from a texture tinted by color fixed4 c = tex2D (_MainTex, IN.uv_MainTex); c.rgb = saturate((lerp(fixed4(0, 0, 0, 0), _RedMappedColor, c.r) + lerp(fixed4(0, 0, 0, 0), _GreenMappedColor, c.g) + lerp(fixed4(0, 0, 0, 0), _BlueMappedColor, c.b))).rgb; o.Albedo = c.rgb; // We keep the alpha: it's supposed to be a decal o.Alpha = c.a; } ENDCG }  

jb-dev

jb-dev

Unity Daily Update #5 - Eternal Ethernet

Today, I've worked on level exits. When the player arrived at the last room before, nothing awaited him. He was stuck for eternity on the same level. Kinda boring, actually... But today this is no more! Now a big Ethernet port awaits the player at the end of the level. He just needs to jump in it to clear the level.  I've had to create two new shaders: one that can fade the screen to black according to the player's y coordinates. I've also needed to modify my main shader to add a new parameter that can create a gradient from the usual colours to pitch black. This way, I can simulate a bottomless pit.  

jb-dev

jb-dev

Unity Daily Update #4 - Crystal updates

Today, I've fixed some bugs with the crystal throwing algorithm. Basically, crystals will be used by the player to get to those alternative paths I've mentioned in my BPS tree entry. There'll be at least 3 type of crystals : Fire, Water and Life. Each will be thrown to eliminate obstacles at the entry point of each alternatives paths. I've also planned them to be persistent throughout runs. This means that the amount of crystals are linked to a save file rather than a run. So if the player didn't used their crystal during the run, then they'll have the opportunity to use them in another one. As you can see, each type of crystal has a particular particle effect attached to them. I've tried to simulate how each type of elements would react. So the fire crystal particles behaves like flames, life one like fireflies and water one like drops of water. I still have to give them a distinctive shape... For now, I've used the default particle sprite provided with Unity. Also, after a crystal hit something, it'll generate other type of particles. These particle will move accordingly to the impact force. So, to recap, I've been working on particles for the past days... Kinda slow, but I think it's worth it...    

jb-dev

jb-dev

Algorithm The power of the vector cross product, or how to make a realistic vision field

In the previous iteration of our game, we decided to use an actual cone as a way to make an AI "see". This implementation was hazardous, and it quickly became one of the hardest things to implement. We eventually were able to code it all, but the results were really static and not really realistic. Because of the reboot, I took the time to actually identify what constraint one's vision has. The visual field First of all, a cone isn't really the best in therm of collision checking. It required a special collider and could have potentially been a bottleneck in the future when multiple AI would roam the level. In actuality, the visual field can be represented as a 3D piece of a sphere (or more like a sector of a sphere). So we're gonna need to use a sphere in the new version. It's cleaner and more efficient that way. Here's how I've done it: foreach (Collider otherCollider in Physics.OverlapSphere(m_head.transform.position, m_visionDistance / 2, ~LayerMask.GetMask("Entity", "Ignore Raycast"), QueryTriggerInteraction.Ignore)) { // Do your things here } Pretty simple, really... Afterwards (not unlike our previous endeavour), we can just do a simple ray cast to see if the AI's vision is obstructed: // Do a raycast RaycastHit hit; if (Physics.Raycast(m_head.position, (otherPosition - m_head.position).normalized, out hit, m_visionDistance, ~LayerMask.GetMask("Entity", "Ignore Raycast"), QueryTriggerInteraction.Ignore) && hit.collider == otherCollider) { // We can see the other without any obstacles } But with that came another problem: if we use a sphere as a visual field, then the AI can surely see behind his back. Enters the cross product. Vectorial cross product The cross product is a vectorial operation that is quite useful. Here's the actual operation that takes place: \(\mathbf{c} = \mathbf{a} \times \mathbf{b} = ( \mathbf{a}_{y}\mathbf{b}_{z} -\mathbf{a}_{z}\mathbf{b}_{y}, \mathbf{a}_{z}\mathbf{b}_{x} -\mathbf{a}_{x}\mathbf{b}_{z}, \mathbf{a}_{x}\mathbf{b}_{y} -\mathbf{a}_{y}\mathbf{b}_{x} )\) This actually makes a third vector. This third vector is said to be "orthogonal" to the two others. This is a visual representation of that vector: As you can see, this is pretty cool. It looks like the translation gizmo of many 3D editors. But this operation is more useful than creating 3D gizmos. It can actually help us in our objective. Interesting Properties One of the most interesting properties of the cross product is actually its magnitude. Depending on the angle between our two a and b vectors, the magnitude of the resulting vector changes. Here's a nice visualization of it: As you can see, this property can be useful for many things... Including determining the position of a third vector compared to two other vectors. But, however, there's a catch: the order of our a and b vector matters. We need to make sure that we don't make a mistake, as this can easily induce many bugs in our code. The funnel algorithm In one of my articles, I've actually explained how pathfinding kinda works. I've said that the navigational mesh algorithm is actually an amalgamation of different algorithms.  One of these algorithms is the Funnel algorithm, with which we actually do the string pulling. When the Funnel algorithm is launched, we basically do a variation of the cross product operation in order to find if a certain point lay inside a given triangle described by a left and right apexes. This is particularly useful, as we can actually apply a nice string pulling on the identified path. Here's the actual code: public static float FunnelCross2D(Vector3 tip, Vector3 vertexA, Vector3 vertexB) { return (vertexB.x - tip.x) * (vertexA.z - tip.z) - (vertexA.x - tip.x) * (vertexB.z - tip.z); } With this function, we get a float. The float in question (or more particularly its sign) can indicate whether the tip is to the left or to the right of the line described by vertexA and vertexB. (As long as the order of those vectors are counterclockwise, otherwise, the sign is inverted) Application Now, with that FunelCross2D function, we can actually attack our problem head-on. With the function, we can essentially tell whether or not a given point is behind or in front of an AI. Here's how I've managed to do it: if ( FunnelCross2D((otherTransform.position - m_head.position).normalized, m_head.right, -m_head.right) > 0 ) { // otherTransform is in front of us } Because this is Unity, we have access to directional vectors for each Transform objects. This is useful because we can then plug these vectors into our FunnelCross2D function and voilà: we now have a way to tell if another entity is behind or in front of our AI. But wait, there's more! Limit the visual angle Most people are aware that our visual field has a limited viewing angle. It happens that, for humans, the viewing angle is about 114°. The problem is that, right now, our AI viewing angle is actually 180°. Not really realistic if you ask me. Thankfully, we have our trusty FunnelCross2D function to help with that. Let's take another look at the nice cross product animation from before: If you noticed, the magnitude is actually cyclic in its property: when the angle between a and b is 90°, then the magnitude of the resulting vector of the cross product is literally 1. The closet the angle gets to 180° or 0°, the closest our magnitude get to 0. This means that for a given magnitude (except for 1), there are actually 2 possible a and b vector configurations. So, we can then try to find the actual magnitude of the cross given a certain angle. Afterwards, we can store the result in memory. m_visionCrossLimit = FunnelCross2D(new Vector3(Mathf.Cos((Mathf.PI / 2) - (m_visionAngle / 2)), 0, Mathf.Sin((Mathf.PI / 2) - (m_visionAngle / 2))).normalized, m_head.right, -m_head.right); Now we can just go back to our if and change some things: if ( FunnelCross2D((otherTransform.position - m_head.position).normalized, m_head.right, -m_head.right) > m_visionCrossLimit ) { // otherTransform is in our visual field } Then we did it! the AI only reacts to enemies in their visual field. Conclusion In conclusion, you can see how I've managed to simulate a 3D visual field using the trustworthy cross product. But the fun doesn't end there! We can apply this to many different situations. For example, I've implemented the same thing but in order to limit neck rotations. it's just like previously, but with another variable and some other fancy codes and what not... The cross product is indeed a valuable tool in the game developer's toolset. No doubt about it.

jb-dev

jb-dev

Unity Daily Update #3 - AESTHETIC++

Today was kind of a slow day: I had many things to do, so development was kind of light... Nevertheless, I've still managed to do something... I've added a way to highlight items through emission (not unlike how we did it previously) and make enemies blink when they get hurt. It wasn't really hard: because this is Unity, the surface shader got us covered. It was just one simple line of code.  #ifdef IS_EMISSIVE o.Emission = lerp(fixed3(0, 0, 0), _EmissionColor.rgb, _EmissionRatio); #endif  

jb-dev

jb-dev

Unity Daily update #2 - Bombs

Today I've worked on adding bombs to the game. They are really useful for dispersing enemies and such. The model was made a while back. It was just a mater of importing it in Unity and coding the script. Here's a nice video I've made just for that: There's nothing really special here, just polymorphism, Unity Components and C# delegates.... Collider[] cols = Physics.OverlapSphere(explosionCenter, m_explosionRadius, LayerMask.GetMask("Obstacles", "Entity", "Player Body", "Pickable"), QueryTriggerInteraction.Ignore); for (int i = 0, length = cols.Length; i < length; ++i) { GameObject collidedObject = cols[i].gameObject; HealthController healthController; Rigidbody rigidbody; AbstractExplosionActionable explosionActionable; if(collidedObject.layer == LayerMask.NameToLayer("Entity") || collidedObject.CompareTag("Player")){ healthController = collidedObject.GetComponent<HealthController>(); healthController.RawHurt(m_explosionDamage, transform); } else if(collidedObject.layer == LayerMask.NameToLayer("Pickable")) { rigidbody = collidedObject.GetComponent<Rigidbody>(); if (rigidbody != null && !rigidbody.isKinematic) { rigidbody.AddExplosionForce(m_explosionDamage, transform.position, m_explosionRadius); } } else if (collidedObject.layer == LayerMask.NameToLayer("Obstacles")) { explosionActionable = collidedObject.GetComponent<AbstractExplosionActionable>(); if (explosionActionable != null) { explosionActionable.action.Invoke(m_explosionDamage, m_explosionRadius, explosionCenter); } } }  

jb-dev

jb-dev

3D Vaporwave treasure models

Roguelites are synonymous with loot and treasure chests. However, my game is vaporwave, so traditional treasure chests are out of the question. This is what I came up with: You may get the references if you know your Windows well enough... 😉

jb-dev

jb-dev

Unity Daily update #1 - wet-dry shader variations

I've decided to make a daily update blog to have a development metric. So here goes... Today, I've modified the shader I've previously made so that it can take a "wetness" parameter. Basically, in my palette, the first 4 columns represents a pair of colors, where as the first ones are dry colors and every other ones are wet colors. I just do a clever lerp between those two consecutive colors according to the given wetness parameter. Here's an example:     Here, you can see that the leaves of that palm tree is significantly more yellow that usual Here it's way more green. The way I did it was quite simple: I've just added a _Wetness parameter to my Unity shader. I then just do a simple lerp like so: /* In the shader's property block */ _Wetness ("Wetness", Range(0,1)) = 0 [Toggle(IS_VEGETATION)] _isVegetation ("Is Vegetation?", Float) = 0 /* In the SubShader body */ void surf (Input IN, inout SurfaceOutputStandard o) { #ifdef IS_VEGETATION fixed4 wetColor; float uv_x = IN.uv_MainTex.x; // A pixel is deemed to represent something alive if its U coordinate is included in specific ranges (128 is the width of my texture) bool isVegetationUV = ((uv_x >= 0.0 && uv_x <= (1.0 / float(128)) ) || (uv_x >= (2.0 / float(128)) && uv_x <= (3.0 / float(128)) )); if (isVegetationUV) { fixed2 wetUV = IN.uv_MainTex; // To get the other color, we just shift by one pixel. that's all // The _PaletteIndex parameter represents the current levels' palette index. (In other words, it changes level by levels) // There are 8 colors per palette. that's where that "8" comes from... wetUV.x = ((wetUV.x + (1.0/float(128))) + 8.0 * float(_PaletteIndex) / float(128)); wetColor = tex2D(_MainTex, wetUV); } #endif // This is part of my original palette shader IN.uv_MainTex.x = IN.uv_MainTex.x + 8.0 * float(_PaletteIndex) / float(128); fixed4 c = tex2D(_MainTex, IN.uv_MainTex); #ifdef IS_VEGETATION if (isVegetationUV){ c = lerp(c, wetColor, _Wetness); } #endif o.Albedo = c.rgb; o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = _Alpha; } Then it's just a matter of changing that parameter in a script like so: GameObject palm = PropFactory.instance.CreatePalmTree(Vector3.zero, Quaternion.Euler(0, Random.Range(0, 360), 0), transform).gameObject; MeshRenderer renderer = palm.GetComponentInChildren<MeshRenderer>(); for (int i = 0, length = renderer.materials.Length; i < length; ++i) { renderer.materials[i].SetFloat("_Wetness", m_wetness); } I've also changed the lianas's colors, but because I was too lazy to generate the UV maps of these geometries, I've just gave them a standard material and just change the main color... And I made a Unity script that takes care of that for me... // AtlasPaletteTints is an Enum, and atlasPaletteTint is a value of that enum // m_wetness is a float that represent the _Wetness parameter // m_isVegetation is a bool that indicates whether or not the mesh is considered a vegetation (this script is generic after all) Color col = AtlasPaletteController.instance.GetColorByPalette(atlasPaletteTint); if (m_isVegetation) { // Basically, we check whether or not a color can qualify for a lerp if ((atlasPaletteTint >= AtlasPaletteTints.DRY_DETAIL_PLUS_TWO && atlasPaletteTint <= AtlasPaletteTints.DRY_DETAIL_MINUS_TWO) || (atlasPaletteTint >= AtlasPaletteTints.DRY_VEGETATION_PLUS_TWO && atlasPaletteTint <= AtlasPaletteTints.DRY_VEGETATION_MINUS_TWO)) { // Each colors have 5 tints; that where the "+ 5" is coming from col = Color.Lerp(col, AtlasPaletteController.instance.GetColorByPalette(atlasPaletteTint + 5), m_wetness); } } GetComponent<Renderer>().material.color = col;  

jb-dev

jb-dev

Unity lets go to the mall (Video)

After really thinking about it, the method I've used to play MP3 wasn't the most flexible, so after re-working it out, I've decided to stream the music directly in a Unity AudioClip. This way, the audio goes through an audio mixer form which I can easily apply filter to... I was also able to cross-fade between two music track. I've also put the sound loading onto another thread, making the audio loading run in the background rather than clogging up the main thread. Also, it's easier to use the 【 VaporMaker】with the Unity Audio system... I can even add more wacky filters over it to make those songs more VAPORWAVE than ever.

jb-dev

jb-dev

Music The 【 VaporMaker】, and letting user play their own music while playing

Vaporwave is synonymous with music. It is primordial that music must be spot on... But with recent takedowns of Vaporwave classics, let's just say that I'm less eager to have sampled Vaporwave included: I don't want that to spoil an otherwise perfectly good game. So I'm probably gonna ship the game with sample-free Vaporwave, made by yours truly. However, that's not the end of it. I'm going to let the user play their own Vaporwave if they like. That way I can secure myself from any takedown possible. I'm also going a step further and created the 【 VaporMaker】 Unity and audio As you're probably aware, Unity can play audio assets that are imported into the UnityEditor. This approach only works with packaged audio, however. This means that we need another way to play external files.  There's a utility class that can be used to play any sound file from anywhere: WWW . This class is used to do simple HTTP requests and catch its results.  If we use the "file://" protocol, we can actually load a file from the player's local machine. And what's more, is that there's a nice method for getting audio clips: WWW.GetAudioClip Cool, let's use that. WAIT, WHAT!?! MP3 ARE ONLY SUPPORTED ON PHONES!?!? That's no good... The workaround So, you're telling me that mp3, the most universally available file format, is not compatible with Unity's audio system? Yes. It appears so... Due to licences issues, Unity cannot be shipped with an MP3 decoder. Which is really weird, but we can't really do anything about it. Thankfully, Unity has C# and .NET, which are one of the most used tools nowadays. I'm pretty sure that there exists a way to fix this. Enter NAudio. NAudio NAudio is a .NET library that can load and play most audio files. This is really useful because we can then use that library rather than Unity's Audio system.  NAudio is compatible with Unity, which is a big plus for us. Of course, we'll need to do a bit of fix around, but it's nothing really hard. NAudio is just a .dll. It's just a matter of dropping it in our Asset repository and voilà: you can now use NAudio in our scripts. Here's the little blog post I've followed if you're interested. Reading metadata Listening to mp3 is fun and all, but I also want the player to know which song is playing. Things like song title, artist, album title and even, if I can, the album cover... Most of the time, these pieces of information already exists within the .mp3 file itself as metadata. This is how, for example, most media players are able to display the album cover of a song. Similarly, this is also how some applications are able to group songs of the same album together. Depending on the used metadata convention, they are either at the very beginning of the file or at the end and can take many forms. We won't need to open a byte stream and manually seek these metadata ourselves. There's already plenty of libraries that are able to do that for us. Funny enough, the solution I've chosen came from the Linux world. Let me introduce you to Banshee. Banshee is an open source media player not unlike iTunes. It can manage one's music collection and play them. This program is written in C#, which coincidently is the same language as our favourite engine... The library responsible for reading such metadata in Banshee is called TagLib#. With a little bit of tinkering, we can include TagLib# in our Asset repository, making good use of it. After creating a UI element containing the metadata, here's the result: (The blurriness is part of the art style, trust me) The 【 VaporMaker】 Now we have both the data and the playback. But I'm not satisfied. Managing the music As you may (or may not know), Vaporwave is basically slowed downed music. Some artist chooses to keep the editing at a minimum, while some add a lot of butter on top, but it all boils down to slowed downed music. The idea I have is to let the player create their own Vaporwave to be used in the game by putting some mp3 file in a special folder. These files will be played at a slower speed than usual, thus creating some rudimentary Vaporwave. Although the idea is simple, NAudio itself doesn't come with such functions... However, they DO have a post on the subject. Basically, we'll add SoundTouch, an open source sound manipulation library. Although written in C++, we can still call its native function with the wrapper given by the post. One drawback is that we'll need to supply native .dll libraries for all platforms if it's doable. A few extra resources (Like a mac and Linux installations) are needed for this if you want multi-platform support, but nothing really hard. (If all fails, you can just copy/paste the source code and fix things here and there) So by following along the source code, we can add the required files in our Asset repository. Easy as pie. Once everything is set up, we'll just need to plug that VarispeedSampleProvider class into our mWaveOutDevice instead of the mVolumeStream like so (if you follow along that blog post I've referenced earlier) private void LoadAudioFromData(byte[] data, bool isVaporMaker) { MemoryStream tmpStr = new MemoryStream(data); mMainOutputStream = new Mp3FileReader(tmpStr); mWaveOutDevice = new WaveOut(); if (!isVaporMaker){ mVolumeStream = new WaveChannel32(mMainOutputStream); mWaveOutDevice.Init(mVolumeStream); } else { mSpeedControl = new VarispeedSampleProvider(WaveExtensionMethods.ToSampleProvider(mMainOutputStream), 100, new SoundTouchProfile(false, false)); mSpeedControl.PlaybackRate = 0.75f; mWaveOutDevice.Init(mSpeedControl); } } When we'll play the song, it'll play at any speed we specified by the PlaybackRate property of the VarispeedSampleProvider instance we constructed.  Managing the art I've could have stopped there, but I STILL wasn't satisfied. I wanted to make a clear distinction between normal custom music and any piece that went through the 【 VaporMaker】.  To do so, I've decided to change the album cover for something more vaporwave. When I fetch the album cover for vaporized songs, I actually map each pixel by their lightness to a gradient of two colours. I've also made those colours members of the MonoBehaviour so that they are available in the UnityEditor. TagLib.File file = TagLib.File.Create(filepath); TagLib.IPicture pic = file.Tag.Pictures[0]; Texture2D text = new Texture2D(2, 2); text.LoadImage(pic.Data.Data); for (int x = 0; x < text.width; ++x) { for (int y = 0; y < text.height; ++y) { float h,s,l; ColorExt.RGBToHSL(text.GetPixel(x,y), out h, out s, out l ); text.SetPixel(x, y, Color.Lerp(m_vaporMakerDarkCoverColor, m_vaporMakerLightCoverColor, l)); } } text.Apply(); Afterwards, when the UI displays the album cover of the vaporized song, it will use the funky artwork rather than the original one, Here, take a look:         With all of this, I'm sure that this feature will be popular, If not only for the ability to play our custom music.

jb-dev

jb-dev

Algorithm BSP trees, or creating a randomly generated level

So the game I'm working on is going to use rooms that are connected to each other by little holes, creating something somehow similar to "Binding of Isaac", but with organic room disposition rather than rooms placed on a grid with specific dimensions. To do this, I needed to search for a good level generation algorithms. I've found that the best algorithm is the BSP trees algorithm, which was traditionally used in old-schools roguelike games. Binary Partition Trees The algorithm works by taking an area and split it in half, thus creating tow new area to be recursively processed by the algorithm. The algorithm can be run until we stumble upon an area of a specific dimension.  This is what that algorithm can do:   Traditionally, each area becomes leaves, in which a random rectangle room is drawn within these. Afterward, each of these rooms is connected to each others using longs corridors. This approach works in 2D, as the player always has a clear view of his surroundings.    Here is an excellent reference on the subject: Basic BSP Dungeon generation Adaptations However, because the game is in a first-person perspective, the corridors won't work as the player can't really know his surrounding very well. We need to adapt the algorithm so that the player can feel comfortable while navigating in our level. I've chosen to eliminate corridors and rooms altogether and instead use the leaves themselves. Instead, each leaf is connected to each other through small holes.  Also, the BSP tree algorithm creates a web-like dungeon with no clear end or start, which is fine if you're making a traditional dungeon, but we want our levels to have a certain flow so that the player can quickly find its way out if they want to. The way I planned to do that is by transforming the BSP leaves into a kind of navmesh grid. Afterward, we just pick some positions and select specific leaves that makes up the path. Creating the navmesh graph First, before we can use the graph search algorithm, we need to build our graph. BSP tree is still binary trees, so using those to deal with connections are out of the question. We need to somehow get all the leaves created in the BSP tree algorithm and put them in a more flexible structure: enter the quadtree. Quadtrees are a kind of tree that can have at most 4 children. This characteristic is quite useful when it comes to 2D rectangles.  Here's a visual representation of a quadtree: With these kinds of trees, it's possible to get every overlapping leaf from a specific rectangle. If for a given room, we query a slightly bigger search zone, then we'll be able to find all of the given room's neighbours. We can then connect everything up and finally launch our graph search using randomly picked rooms that are far enough from each other. Do the pathfinding I've already made a blog entry on pathfinding so the procedure is almost the same... However, there is some difference here... One of the most important difference is that we add the concept of "hot" cells. When a specific cell is deemed "hot" and that the graph search algorithm stumbles upon it then its cost will be infinite. That way, we can say to the algorithm this: "Do not pick this cell unless it's your last option". This makes for a somehow imperfect path... But in our case, imperfect is perfect.  Afterwards, we add all of the chosen rooms in a final list. All rooms in this list will be part of our level and will be rendered out later on. Add more rooms After we picked the main rooms, we can then append bonus rooms to some of these main rooms if the player is lucky, not unlike hidden rooms in "Binding of  Isaac"... Also, the game is going to sometime have an "alternative path". These paths will try to be shorter than the main path and overall have more bonus rooms and loot to them. I've planned that the player needs to fulfil some requirement to enter this path. Because we already created a graph of each possible rooms, it's just a matter of luck to see if a room has a special room connected to it. Rendering it out Once the rooms configurations were made, we now need to create the geometries and collisions of the level. Before going with the BSP approach, I've tried to use cellular automata to generate cave-like structures... It wasn't controllable enough, but I've kept some of the code from it (mainly its geometry generation) Here's the cellular automata tutorial Basically, we render each rooms pixel by pixel. We then cut those "holes" I've talked about earlier and voilà. Here, I've coloured each room to give a better idea of what kind of room each is which. Blue rooms are part of the alternate path I've mentioned before. The green and red rooms represent both the starting and ending room respectively. Yellow rooms are bonus rooms. Afterward, it's only a matter of placing props and enemies. This method of creating levels is cool. It can make the game more flexible and interesting. It also all depends on luck, which is a stat that can change in-game.

jb-dev

jb-dev

 

Updates

Hi guys, I have a bad news and a good news. The bad news is that the game i was currently working on is kinda canceled. But, however, this is not the end of this endeavor. I've chosen to continue the development on my own and with Unity.  Turns out that the previous engine we tried was missing a lot of key components that was needed for our project.  Paired this with other intrapersonal problems and our team was dissolved. I, however, still believe in the idea. The feedback was somewhat positive, and I'm sure that if I give my 100% on this that i might get a chance to make you believe in it too.   So hang on tight, because the ride is far from being over.  

jb-dev

jb-dev

Design Windows-like pause menu and color computations

So the game we develop is growing steadily. We've already added a pause menu. Its function is to be a... pause menu. (I don't know what you expected...) The design Because our game is going to be really Vaporwave, we knew that the visual had to be on point. We ended up trying a classic Windows-like design with header bars and everything, but with a twist... Here's the result: (Note that not all buttons are fully functioning. Also, the seed isn't actually used in the generation) The idea is that this window appears when the player pauses. It takes the form of a popup with fully functional tabs. We also plan to let the player easily navigate through the tabs with keyboard (or buttons, in the case of a controller) shortcuts. In addition, our game uses palettes, so the GUI elements are colored according to the active palette. Here's a example with a different palette: LESS-like color computations You may have noticed that there is a difference between each palette (for example, the title of the window has changed color). This is done by a beautiful library that I built for our project. Because I was a web developer for about 2 years, I already knew (and worked with) CSS compilers like SASS and LESS. My library is strongly inspired these compilers. Especially LESS. The luma value For this reason, I knew there was a way to know if a text of a given color would be readable when displayed on a given background. This feature is present in vanilla LESS : it's called "contrast".  That function uses the luma values (sometimes called "relative lightness" or "perceived luminance") of colors. This small practical value describes the perceived luminance of a color, which means that particularly brightly perceived colors (such as lime green or yellow) gets higher luma values than other colors (red or brown) despite their real lightness value. Here's how I compute a given color's luma value: Color color = Color.GREEN; // Fictionnal class, but it stores each components as floating points values form 0 to 1 float redComponent, blueComponent, greenComponent; if (color.r < 0.03928f){ redComponent = color.r / 12.92f; } else { redComponent = Math.pow((color.r + 0.055f) / 1.055f, 2.4f); } if (color.g < 0.03928f){ greenComponent = color.g / 12.92f; } else { greenComponent = Math.pow((color.g + 0.055f) / 1.055f, 2.4f); } if (color.b < 0.03928f){ blueComponent = color.b / 12.92f } else { blueComponent = Math.pow((color.b + 0.055f) / 1.055f, 2.4f); } float luma = (0.2126f * redComponent) + (0.7152f * greenComponent) + (0.0722f * blueComponent); The actual luma computation is fully describe here. With that luma value, we can then check and compare the contrast between 2 colors: float backgroundLuma = getLuma(backgroundColor) + 0.05f; float textLuma = getLuma(textColor) + 0.05f; float contrast = Math.max(backgroundLuma, textLuma) / Math.min(backgroundLuma, textLuma); With that, we can choose between tow color by picking the one with the lowest contrast: Color chosenTextColor = getContrast(backgroundColor, lightTextColor) > getContrast(backgroundColor, darkTextColor) ? lightTextColor : darkTextColor; This can give us a lot of flexibility: especially since we use many different color palettes in our game, and each with different luma values. This, along with more nice LESS colors functions, can make coloring components a breeze. Just for example, I've inverted our color palette texture and these are the results:   Yes, it looks weird, but notice how each component is still fully readable. Paired with our dynamic palette, color computation is now really easy and flexable.  

jb-dev

jb-dev

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!