Developer Diary #2: The Simplistic Platformer AI

That Skipable Preamble.

It’s only been about 3 months since I first opened Unity3D. The interface alone was daunting. Up till that point I was using Buildbox, a Stripped to the raw essentials game making tool. Unity3D is a beast, a titan in comparison. You have a high level view and can zoom all the way in to the raw code that makes everything work. With Buildbox, you only have the high level view. What lurks beneath is comply hidden from view. This is a blessing and a curse.

BuildBox has no AI. It’s all path driven behaviors. There’s nothing cool or fancy about it. The games you can make are super limited. Thus the market is flooded with Flappy Bird and Bullet Hell clones. I was spoiled with the luxury of not thinking as I assembled graphic art and put together basic games. But I wanted more, something real. I hate mediocrity. As much as I love “Rocket Shark” and “Drill Deeper” they were mediocre. Simplistic, fun games to pass the time while waiting for your coffee. There’s absolutely nothing wrong with that. But I want to give more, make bigger, better games. Of course time and money at this moment are at a premium, I need to start very small and work my ass off to get where I want. Yes, my ass is literally worked off. It’s numb as fuck sitting 16 hours in this worn out Ikea chair.

So I fronted some cash, and bought a prefab Platformer engine. Time again. I needed a shortcut. Something up to the task of getting a decent, quality game published. Boy that was a mistake. $500 in graphical assets and 100 redo’s later I’m finally on the right path. Yeah, I’ve been running myself thin, this is my break. A collection of fragmented thoughts.

Simple AI is NOT Simple

So that prefab engine I got, was a holy cow mess. The code was a nightmare. I have a programming background since College days, so I know shit code. Aside from that, I’ve spent the past year sitting in front of Udemy programming classes 8+ hours a day. Classes and book work does not make a good programmer though.. Getting out there and actually doing it does. So I opened the monster code and got terrified. It was like staring into the abyss and seeing it look back at you. The terror it sends down the spine shaking your very soul.

I spent the last 4 days working on the AI for one character, the typical “goomba”. Despite being a 2D engine the guy used a mashup of 2d and 3d Unity calls. It generally “worked” but weird things were happening. He used a maxX and minX variable with a Vector3 clamp to keep the character where it belongs. Not a big deal right? Wrong! When dropping a prefab into the scene, the monster “vanishes”. As I later learned, clamp is like a cage. It will forcibly put anything back within it’s grasp. So I unshackled my Goobma.

Without Gravity, without the chains to bind him, my goomba would just walk away. Through walls, through everything to escape the scene bounds. The guy (previous “developer”) cheated in an extraordinary way. That goobma didn’t give one f*ck. He was outa here.

So I set up a Test Lab

I needed a scene where my goomba could play happily without fear of being head smashed. I created a simple scene from some block prefabs and put them all together.

Unity3D Simplictiy
This was my view for dozens of hours

I hate that scene. But it yielded fantastic results. At first I thought I succeeded, but forgot to turn off clamp. Fuck “Clamp”. Then he still passed through walls, even with RigidBody and Boxcollider2D. Then I discovered the beauty of Raycast. Designed for bullets and projectiles, useful for so much more. But the damn goomba still walked through walls.

It’s all About the Angle

Have I told you I started Unity3d 3 months ago? Yeah, so I was just sending rays all over the place. I figured out how to use Vector2 directions to get down to a single Raycast in the direction my goomba was going. Bingo, he dodged walls. Next up, not falling off the platform.

This was simple right? Cast a ray at a 45 degree angle from the direction the goomba is walking? Well in theory yes. The original developer was tracking direction as a plus or minus 1. This needed to be converted to a Vector2. Finally the X coordinate was fine, I just needed to add in a negative Y and got my 45 degree angle.

Now I’m getting somewhere.

Great. It worked. Set up a bool to tell if I want him to edge detect or not and I have a working goobma. But…

He ended up freaking out at the crates and “drilling” his way through the floor. After a few hours of “WTF Man”, I discovered it was a very simple fix. The BoxCollider2D was off by a few pixels. So the straight down RayCast was registering that one pixel gap as both an edge and not ground sending my goomba on a frenzied search for sanity.

I fixed all my prefabs and now he works.

There’s a Lesson in all this

It’s not like I lost 4 days development trying to rework shitty kludged AI. I learned a lot on how to work around Unity3D’s flaws. I had to simulate my own falling gravity arc for the goomba. I’ll have to do it again for other characters. But I now have a pretty decent platformer AI scaffold. From here I can build the other characters. The flying bats and skulls. The angry cats and pissy squirrels. The foundation of my goomba will become the basic AI of my more advance characters.

Oh shit philosophy!

Yeah, so I see the countless hours of “failure” as learning. I’ve adjusted one system only to break 10 more. Just today after completing the Goomba, I realized I had broken the Player’s Cling ability. That only took a few hours to fix because of everything I learned from the whacked out Goomba. Because of my struggles, the future implementations will become that much easier.

Anyway, holy cow this was a long “blog”. If you read this far, you’re awesome and thank you so very much.

 

 

About Craig

Craig is the founder of The Chaos Rift and developer of the games published here. In his spare time he'll also write about games, play games and dream about games. Being a Game developer has been a dream of Craig's since he was 14 and after some detours has finally started to realize his dreams.

Check Also

unity 3d lerp

Developer Diary: I’ve been LERPing wrong this entire time!

LERP for Fun and Profit Updating and fixing a massive amount of bugs in “Super …

42 comments

  1. Looking for a fun way to pass the time? I definitely recommend playing lucky57game site and have fun. Check information here: lucky57game

  2. Alright, GameQQ88, lemme tell ya. Games are solid, graphics are slick, and the vibe is cool. Ain’t gonna lie, I’ve spent a chunk of time here. See for yourself: gameqq88

  3. Mxbetcasino, un casino más para la lista! Ya veremos si vale la pena. A ver si la pasamos bien y ganamos algo. Visita mxbetcasino.

  4. Saw 7700bet777 advertised somewhere. Gave it a quick look. Pretty much what you’d expect. Worth a shot if you’re bored. Head over to 7700bet777.

  5. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  6. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  7. The Top Online Casino and Slot Games Destination in the Philippines visit: slotphlogin

  8. Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.com/register-person?ref=IXBIAFVY

  9. Понравилось общение, подсказали вариант. Доставили вовремя, букет красивый!
    букет невесты томск

  10. Курьер позвонил заранее, привёз в нужное время, очень вежливый.
    https://plotmaster.in/author/linneacarrasco/

  11. Заказывала букет маме — композиция получилась нежная, доставка точно в срок.
    https://www.youmanitarian.com/tv/@elva6002445782?page=about

  12. Розы в сердце влюблённой девушки — спасибо за эмоции и прекрасную доставку!
    https://www.vytega.com/employer/kupitrozyvtomske-1/

  13. Очень понравился выбор — букет получилось подобрать под настроение.
    https://git.wieerwill.dev/penneylindstro

  14. Заказала утром — к обеду уже доставили, просто замечательно.
    https://gitiplay.com/@douglaskohl516?page=about

  15. Опытные специалисты предлагают сделаю прогон хрумером https://www.olx.ua/d/uk/obyavlenie/progon-hrumerom-dr-50-po-ahrefs-uvelichu-reyting-domena-IDXnHrG.html, используя проверенные базы.

  16. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  17. Обожаю этот сервис доставки, уже третий раз заказываю — всегда на высоте.
    розы томск

  18. Оформила заказ онлайн, боялась, что опоздают, но курьер приехал вовремя, букет шикарный, свежий и аккуратно упакованный.
    доставка цветов

  19. Теперь, если нужны цветы в Томске, даже не думаю — сразу оформляю доставку здесь.

    https://dostavkacvetovtomsk6.ru

  20. Заказывала букет из роз парню, сделали стильную, не приторную композицию, получилось очень уместно.
    51 роза томск купить

  21. ?Доставка не подвела, курьер заранее позвонил, уточнил, удобно ли получить, всё по-людски.
    заказ цветов томск с доставкой

  22. Очень ответственный подход: уточнили детали по телефону и организовали идеальную доставку цветов в Томске.

    dostavkacvetovtomsk6

  23. Получилось даже лучше, чем ожидала! Фото в каталоге совпадает с тем, что доставили, редкость в наше время.
    розы томск

  24. Сервис по доставке цветов в Томске показал высокий уровень клиентского сервиса.

    букеты томск

  25. Заказала нежный букет из роз для сестры, она сказала, что в жизни он ещё красивее, чем на фото.
    белые розы купить томск

  26. Очень довольна результатом, обязательно порекомендую друзьям.
    цветы томск

  27. ?Заказала для бабушки простой букет, а вышло прям очень мило и трогательно, она до слёз растрогалась.
    купить розы в томске

  28. Букет стоял долго, доставка по Томску отличная.

    заказ цветов томск с доставкой

  29. Букет для директора в администрацию Советского района привезли вовремя!

    доставка цветов

  30. По Томску букет бомба.

    доставка цветов

  31. Очень выручили: оформил заказ удалённо, а в Томске уже через час вручили шикарный букет.

    букеты томск

  32. Очень порадовало, что букет из роз не был перегружен лишними деталями, всё стильно и со вкусом.
    купить букет роз томск

  33. ?Заказывала в последний момент, и всё равно сделали красиво, без ощущения, что торопились.
    букеты томск

  34. Удивительно, но даже фото перед отправкой прислали — супер сервис.
    заказ цветов томск

  35. ?Классно, что можно подобрать букет под характер человека, а не только под повод.
    заказать цветы томск

  36. Сразу видно, что флористы имеют чувство вкуса и знают тренды.
    купить цветы томск

  37. Heard about jlcc from a friend. Pretty solid, actually. Not bad at all! Have a look at jlcc jlcc and see for yourself!

  38. Oxxocasino surprised me, tbh. Didn’t expect much, but the bonuses are pretty sweet and the variety of games is impressive. Gave me a pretty good experience overall. Press this link here oxxocasino!

  39. Yo, cf789live! Just checked this out, looks pretty slick. Gonna give it a spin tonight and see if it’s the real deal. Fingers crossed! cf789live

  40. Сервис доставки цветов Томска произвел впечатление продуманностью мелочей.

    доставка цветов в томске

  41. Классные букеты с доставкой в Томске.

    доставка цветов томск на дом

  42. Букет “Радуга” из разноцветных роз – взрыв эмоций и восторженных криков!

Leave a Reply to lucky57game Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.