Collision Avoidance using Raycasts in C# Code Snippet


I just add some pretty good code for collision avoidance in Space Warfare… Most code ideas I found around the nets about collision avoidance use the same block of Unity Javascript. Well, Javascript is taking a back seat in Unity pretty soon and I don’t really use it. I thought other folks might like the same code snippet in C#. Here it is!


//subtract AI thing’s position from waypoint, player, whatever it is going towards…

Vector3 target = targetYouAreFollowing.position – transform.position;

//normalize it to get direction
target = target.normalized;

//now make a new raycast hit
//and draw a line from the AI out some distance in the ‘forward direction

RaycastHit hit;

if(Physics.Raycast(transform.position, transform.forward, out hit, 800f)){

//check that its not hitting itself
//then add the normalised hit direction to your direction plus some repulsion force -in my case // 400f

if(hit.transform != transform){
Debug.DrawLine(transform.position, hit.point,;

target +=hit.normal * 400f;


//now make two more raycasts out to the left and right to make the cornering more accurate and reducing collisions more

Vector3 leftR = transform.position;
Vector3 rightR = transform.position;

leftR.x -= 2;
rightR.x +=2;

if(Physics.Raycast(leftR, transform.forward, out hit, 800f)){
if(hit.transform != transform){
Debug.DrawLine(leftR, hit.point,;
target +=hit.normal * 400f;

if(Physics.Raycast(rightR, transform.forward, out hit, 800f)){
if(hit.transform != transform){
Debug.DrawLine(rightR, hit.point,;

target +=hit.normal * 400f;


// then set the look rotation toward this new target based on the collisions

Quaternion torotation = Quaternion.LookRotation(target);

//then slerp the rotation
transform.rotation = Quaternion.Slerp(transform.rotation, torotation, Time.deltaTime * 100f);

//finally add some propulsion to move the object forward based on this rotation
//mine is a little more complicated than below but you hopefully get the idea…

transform.position += transform.forward *20f *Time.deltaTime;


Thanks to and for explaining the concept to me. If any readers are having trouble, check those sources… My numbers for distance and repulsion are based on spaceship moving at high speeds. The examples show slow moving spheres so their numbers might work better.

Next I will be adding a case where if all three raycasts hit you need to move one way or another. Otherwise, everything cancels out just about and ships still crash into stuff and explode. I kinda want that to happen a little bit so that you can feel like you are in a good asteroid chase scene, but not so much that it is over in seconds…

Dev Log: Space Warfare Infinite – New AI tricks, missiles for everyone! and Unity3D Bloom findings

screen_78.26921Over the past week I’ve been having a lot of fun with Space Wars, while also researching and reading about AI. (I also got a little sidetracked by trying to perfect the bloom image effect….)


AI can make a game like Space Warfare pretty exciting. I plan on having some multiplayer aspects once I get the major systems together, but the focus of the game is really a single player experience at this point. Since that is the case, cool AI pilots who behave in interesting manners is important. My actual AI code at this point needs to be refactored because it is a big mess, but the things its doing already even without a really nice organized OO state machine are pretty fun. I plan in the future to build out more of a Playmaker-esque state machine for these guys but it’ll take some focus. Because of the behaviors of the AI, the game is becoming pretty fun to watch. It has the enemies turn and loop and barrel roll to escape or ambush each other.

Current states include Chase, Attack, Reposition / Flee. Within those states the ships are able to barrel roll in reaction to being hit as well as change target focus. My idea is that I want to have some base states like Attack and then have a bunch of maneuvers that can be employed by the pilots depending on their style/personality/status. I am looking into multiple temporary short range ‘waypoints’ to create maneuvers so that AI can do looks or spiral at another ship instead of go in a straight line.

Some of my research to me to the above really cool video from Star Citizen (disclaimer: I am one man, Star Citizen will always be cooler than my game…). It hints how they are thinking about AI and displays some quick shots of the Ai engine. I can’t afford to hire that Ai company but I like some of their approaches. One of the things they really focus on is collision avoidance which made me think – oh man I don’t have anything to collide with yet other than really small ships better get to work on that! Unity’s Nav Mesh seems out because its a 2D plane and not a big open space. I’m heading towards a raycasting set up for individual ships. I forsee it being a little costly so I might have to add some collision radius objects that trigger the raycast steering only when necessary. One video that seems to explain the basics is here: Sadly the author seems to have disappeared from the internet and never continued the series.


I’ve also implemented missiles into the game. They are basically have perfect tracting to the only way to not get hit is to accelerate long enough that they can’t catch up or have them hit or get hit by something. I am working on a few countermeasures like a ‘chaff’ like drop and perhaps flares. I know chaff is for radar, but I might make it a dual purpose item in this game. It just drops a bunch of chunks of metal behind the ship that can clog an enemy radar with blips or set off a guided missile if a chunk collides with it. The other balancing option I will add is the length of time the guidance system works. This will give the player the ability to outrun then dodge a missile over a range if the guidance cuts out early, but is still a threat if the ship remains on the same course.

When I have add the ability to upgrade, ships could by better missiles with longer range guidance systems to make them harder to shake. As it stands now, unless your opponent launches a missile from too far away, the likely outcome is an explosion. Its so likely that for the above video I needed to disable missiles just to show you the Ai fighting without immediately creaming each other with missiles. Also I wouldn’t be able to stay in one place and film for my that 10 seconds before getting hit myself.

Missiles are a powerful weapon. But I always feel they are underpowered in games. Perhaps I should make it a little more random – 10% chance of surviving a missile? Perhaps its time to add shields!? Also individual parts of ships might mean less instant kills if its not a direct hit.


On the Bloom front… well the game is shiny now! Look at the before and after!






Things I’ve learned so far… some Unity image effects may be added after every camera is rendered. This means that no matter what camera you add an effect to, everything is gonna get the effect. The bloom happened on all my cameras no matter what my order was or culling set ups were. I’ve tried it all…. If someone out there reads this and finds out a way to make my findings untrue, I would love to see the solution! Comment, twitter, email me!

The main problem I’ve had is that the really nice Space for Unity scenes were getting over exposed and washed out so that you couldn’t enjoy the scenery. Since the main thing I wanted blooming were the trails and lasers, I ended up really brightening the particle materials they were using and then turning up the ‘threshold’ setting on bloom so that everything doesn’t wash out. It sort of works. I like more glowing than less so I am happy where I am with the look. Sometimes I feel like almost Bloom alone makes the Unity Pro license worth it — just the cool factor.

Dev Log: Space Warfare Infinite Updates -Bloom and Ai

I know I should be working on my November game, but the prospect of being able to devote more time to Space Wars (As well as finding a real game name for it – Space Warfare Infinite?) has been too tempting! I will get back to my monthly project soon, but  in the mean time lets talk updates to Spacewars.

Bloom –

Bloom is all the rage. It’s the main reason to get Unity Pro from what I can tell. That and the profiler. But lighting effects take your game and put it in the pro category – at least with the looks. I’ve been trying a bunch of different post-processing effects, but standard bloom seems to be the best for making space object look interesting and making laser flash and glow. The battle now just seems more alive! The downside is that brighter backgrounds glow too much and look too bright. At the moment I am just letting it slide. I fooled around with the camera render orders and such but could never get the bloom to only effect lasers. So far it doesn’t seem possible for me. (I did see someone wrote a shader that keeps bloom from rendering on something. I might do something like that someday to fix the nebulas and other stuff I don’t want to glow).


Ai –

I’ve also been futzing with the Ai. I really want to write behaviors and more decision making. The current Ai chooses a random target from a list of enemies and then blindly charges. When in range they start firing. The other behaviors include: if they get hit a couple time in rapid succession, they will find a random waypoint to run off to; if they are attacking for more than a few seconds they will find a new way point to back off and then go back to it; if they get hit by a ship that is not their target a few times, they will switch targets and defend themselves.

Last night I changed a few things that annoyed me. First I added a lead object to each ship so that ai will aim just before the target thus leading their shots. Works well for moving objects.

I want to build a behavior where the Ai does flybys or other maneuvers that make sense. As I step towards that, I removed their ability to stop. It looked super dumb to see ships just floating in space taking shots. I just have them thrust at all times now. I also dropped their rotation speed from 20 to 1 which makes them curve a little more when flying – looks more natural. No more turning to the player in a blink! I also want to add a behavior when they are too close for more than a few seconds, find a nearby waypoint to go to before attacking again — the ai seems to get in close and then circle the target without being able to aim shots. They need to be able to get a new attack vector. The movement makes the game much cooler looking. Everything circling around with trails.

Ai Behaviors I am hoping to put in:

  • Rush pass / loop: Ship flies by target attacking as they pass then pulls up and executes loops to do another run on same strike vector
  • Flanking loop to hit target from side Circle to get around and behind target Go to waypoint
  • Patrol series of waypoints
  • Follow / Protect target
  • Follow / Copy target (attack its targets) Stand still – cap ships will prob do this alot Kamakazi ramming
  • Strafe side – get up to speed then rotate to aim guns at target let inertia carry ship along side target while unloading weapons… (currently not possible in way game handles ship flight… but this might be an effective attack for fighters against a cap ships PDS)
  • Preferred targets – weakest, injured, toughest, untouched, ranged, fighter, cap, midrange, auxilery, stationary, slowest, low shields, low armor, high shields, high armor, no ‘type’ gun, specific ship
  • Scanning / Sight Range- how far should awareness go? Should be increased by auxiliary scanning ships in fleet.
  • Use specialized component – Scanner Jammer, EMP, Cloaking,

Live Streaming and Video Tutorials – Playing Strike Suit Zero on

I’ve figured out how to set up a account and how to do better screen cast videos on my computer. I hope to have better videos (HD) to show off future games. I also hope to start doing more How to Make Games tutorials for beginners on the web and my students. The Badger Head Games channel is and my Youtube Channel is I’ll post relevant videos here, but you can subscribe to those channels as well.

As you will see from the video, while I love making games, I am not the best video game player! While I enjoy playing games, I also play stuff that I can get ideas from. The folks behind Strike Suit Zero have made a pretty impressive space battle game. I love the feeling of being in a big space battle with lots of fighters and capital ships flying around. The mission in the video also has a space station. I spend a lot of time trying to blow up a frigate and take lots of damage getting hit by its turrets. Each turret is targetable and destroyable. In my game, charging into Point Defense Turrets like that will probably make for a quick end to your ship. Taking out cap ships will require some strategic targeting of the defensive guns before making any type of bombing run.

Things I love about Strike Suit Zero:

  • Big cap ships engaging in battle
  • Nice small fish in a big fight feeling
  • Engine trails that make it easier to see enemies
  • Turrets on ships
  • Cool HUD targeting system – arrows pointing to available targets, boxes on targets, circle that tells you you are aiming right
  • nice explosions, shield effects, player hud static effects when damaged.
  • Comms w headshots  – moves story along with cinematics
  • Being able to survive but still lose a mission (sometimes the game doesn’t continue on tho, you have to play until victorious)

Anyway, look forward to my future videos. I am planning to make an intro to Unity tutorial featuring hover tanks and rockets. It should be an ‘easy’ to follow tutorial to get folks started on making their own Unity games.

Dev Log: The State of Space Wars and October’s Game

Over the last few months I’ve been teaching myself various programming strategies and concepts so that I might one day put together a complete version of Space Wars (or whatever it will officially be named.) I have made a a few 3D space combat games, a 2D multiplayer space combat game, some mobile games, some first person shooter games, even some games that were more about explosions and effects than anything else. All of these games are stepping stones to help me work out problems and figure out what will ultimately make my game the way I want it.


Last month, I created a rendition of a space dog fight game as well as procedurally generated star systems linked by jump gates. The map system was never implemented and thus you can never really travel back to previous locals. In fact, the game is so randomized, you might not ever see the same star system again! One sticking point was that I wanted to link the systems so you could fly back and forth, but in the end didn’t code the algorithm to make it work.

Things that really stumped me were: if the system is generated randomly, how do you know you have enough jump gates, if no real map exists how do things link, can you randomly generate a map and fill it with random star systems? How do you account for cool stuff like space stations or enemies if everything is generated randomly? What about planets? How will the game know what type it is, if there are cities there or animals or mining resources? We were getting into Dwarf Fortress level thought experiments like — what about history generation, empire generation, colonial expansion of factions, ancient civilizations wiped out with remnants on desolate planets like that scene in Guardians of the Galaxy. All these things are possible, but they will need some thoughtful coding.

This month I want to do some random map generation that I can apply to the space system problem in the future. However, since it is October, I think it is necessary to do a horror themed game! My idea is a procedurally generated ‘castle’ map of corridors and rooms with doorways. The map will build on the fly, have a starting point and at least one exit or goal. The castle will be haunted, of course, by 3D pacman style ghosts who will chase the player, but will also be easily fooled making for a stealth hide and seek element of gameplay.

In the end, this map generator will be able to port to my space games because doors will become jump gates, the rooms will be the random star systems. Perhaps the starts and finishes could be starting points for home systems of various factions. Whatever method I use to store data about the maps might be my way of implementing space stations and things. At least some of the needed code will be generated this month despite not working on a ‘Space Wars’ game.

When my #1GAM challenge is over, I plan to devote most of my programming time to working mainly on a real space wars game — exactly what I was doing before I started the challenge. Of course, now I know a lot more than I did back then!

Dev Log: Space Wars now has missiles! And it’s pretty… #1GAM

Screen Shot 2014-06-17 at 10.50.58 PM

A little more progress this week – I’ve added in multiple cannons and missiles to the mix. The missiles involve targeting enemies which I made automatic by just aiming at them. Aiming puts a red box around the enemy that is currently being targeted. From their a missile will chase the target for a period of time usually resulting in a hit. I tried all sorts of ways of doing the missile trajectory and while big arcing ones looked cool, they resulted in lots of misses. So the current missiles are pretty vicious and accurate. Check out the video of some highlights…

Another added feature is I’ve included Space for Unity assets in the game. They are much cooler looking than my stuff and I picked it up a long time ago so it’s best I put it to some use. In adding the cool planets and nebulas, I also expanded the map to about 4000 square units. Seems big enough to explore now. The mini map is a little crammed but I have plans to make it a little more zoomed in and then have an expanded area map UI at some point.

I’ve noticed with some of my updates, I need to test again online since some of the effects only show up for one player. Also the enemies are super jumpy if you are not the server it seems…

I’ve also been trying to figure out an offline mode but the Photon directions are unclear how to implement it… 🙁

Space Wars Update – Video with Scores, Sound, Hit Points!

I’ve added better(?) AI, explosions, sound effects as well as hit points and a score to the game. It might be getting too complex for the webplayer soon. We may need to switch to stand alone PC/Mac downloads. Here is a link to the web version of Space Wars…

Rewatching the video, I notice the AI is doing a lot of spinning. I am still trying to figure out how to make the AI better, I’ve tried a lot of things. Sometimes it works great, sometimes it does random silly things while it works out its rotation. I plan to implement a waypoint patrol ai, a search ai, a follow/guard ai and a defend area ai soon… Those will be sooner rather than later. Further on I’d like to have goal oriented AI and preferred targets where AI will assess enemy ships and decide what is the most important target. Fighters set to skirmish mode will rate other fighters highly as potential targets, but other fighters whose mission is to destroy a space station or carrier might skip other fighters to prioritize travel and attack their main target. This will be important as ships diversify, we can have capital ships chasing every little fighter buzzing around them if there is an enemy cap ship pumping them full of lasers…

Also up for the AI will be factions so that some AI bots can be on the player’s team. Then the real space war will commence…


Basic AI Ships added to Space Wars Net

I’ve added some enemy AI ships to the game to chase around players. You can team up and try to take them out. They are fast and vicious and they respawn just like you do.


Having been testing the game with by myself, it is pretty cool to have some ships to fight against. Now I just need to make them smarter and maybe easier. Next up capital ships – but I will need to program some turrets and some missile style weapons too.

Space Wars Net Update – Bigger Arena, Better Network-ish, Mini Map, Explosions!

This week I’ve been re-working my May game into a remake of an older Javascript game I made a year ago. I want to keep the networking part of the game while building out big space battles with AI. At the moment its more of a dog-fight game for multiple players. Here is a link to Space Wars Networked…



Mini Map! – One major upgrade that I also had in my old game – I now have a mini map that gives you some idea of where you are which will help as area to fight in and explore is bigger than before. I think the real levels will be bigger than this. Hopefully the mini-map will work even better in future iterations.


I haven’t come up with a graceful way to avoid using OnGui – almost every guide prefacesthe use of OnGui with a warning that one shouldn’t really use it in gameplay because it a framerate hog, but then no one has really offered up a different way to place semi-static stuff on the screen over the gameplay. Perhaps a second camera viewing Quads that don’t move that is overlayed over the main camera? How many camera would it take to become a framerate hog too? For now the gui works but that might be something to look into.

Syncing over Proton: One other problem I am noticing – at least on my machine is that positions aren’t synching too well. Shots that look like they will hit miss or don’t result in a hit/explosion while other times what appears to be a wide shot for one player, results in a hit… Not cool really. I may have to network sync all the lasers – but again that sounds like a very unoptimized way to do things…

Enemies: It is time to bring the war to Space Wars. I am going to spend some time tonight trying to get some enemies into the game. I am not sure how it will work exactly over a multiplayer game with syncing etc. I will start with simple AI like fly to waypoints and chase the players. There are no walls to worry about so pathfinding should be a breeze. I’ve been looking into more realistic steering behaviors, but I am going to brute force it for now…

Dev Log: New Space Wars Game, Trying Photon Networking

With the month of May behind me, I am fully immersed in Unity Networking. The month taught me that multiplayer game making is possible, but incredibly slow and frustrating. Many hours of potential coding were spent staring at the screen, reading the same tutorials and still not getting this old dog brain to learn new trick. In the end a game was made. Not perfect, not polished, but it worked! We played it in my school game club after school program and the kids loved it. Maybe it was because they didn’t have to do their homework and I don’t let them play Minecraft, but they seemed to enjoy blowing each others spaceships up and crashing into planets. The whole experience made me think that having some form of networking is needed in most future games, so the month of June will be partly devoted to that. But I’m also working on something else…

My goal this month is getting a SpaceWars 2 remake up and running in Unity. (Above is a clip from the Unity version). Its been a crazy journey to get here, but the ridiculous thing is that I began learning Unity so that I could make this game better. I wrote the original SpaceWars 2 remake in Javascript using ThreeJs but quickly found that the whole thing wouldn’t come close to a compiled game in terms of frame rate when supporting the massive battles I had planned.

The game supported a pretty good amount of ships at a time and it includes turrets, capital ships, bases, as well as systems damage where if you take hits you potentially lose engine power, shooting ability, shields etc. A lot of complicated javascript! The ai wasn’t horrible either. But I am sure I’ve learned something in the last year in terms of game design.

Additionally, I want the big space battles to be able to include friends. Have buddies join the fight with you as a squadron in a giant battle. I think the idea could be lots of fun. Sort of Gratuitous Space Battles where you are one of the little fighters getting destroyed…

As for the networking component, I think I am going to try something new and move from the Unity native networking to the Photon network. The free version allows for 20 players and it handles a lot of the server hosting so we won’t run into the troubles of hosting servers on player computers.