A Fuzzy Logic Based Autonomous Car Simulation in Unity Justyna Walotek1 , Jagoda Oleksiak1 , Pawel Cebula1 , Adam Stanek1 and Mateusz Szczypinski1 1 Faculty of Applied Mathematics, Silesian University of Technology, Kaszubska 23, Gliwice, Poland Abstract Our project focuses on using fuzzy logic to make a car drive by itself. Autonomous cars are nothing new nowadays, but the path that we took differs from what is commonly implemented in such cases. When searching for a self-driving car, most of the results rely on a neural network, that learns how to navigate through the track. The issue with this approach is that the network only knows this one particular track and any other track would require training the network all over again. Our idea was to make a car, that would be able to navigate through any given track without the need to learn how to do it. To better describe the technologies that we used first we need to talk about the history of games and AI, then move focus to the more technical aspects of this project, including how the car gathers input and how it is being analyzed, to then cover all of the tests conducted on different car settings consisting of weight, drivetrain and maximum torque, finally reaching our small contest between AI and two different players. Keywords unity, fuzzy, car, simulation, game 1. Introduction 2. Related works To understand the connection between video games and Among other works related to the topic of games, game artificial intelligence we need to know how these two theory, and fuzzy logic, we can mention ’A Game The- came into existence. Let us focus on games first. In Octo- oretical Based System Using Holt-Winters and Genetic ber 1958 physicist William Higinbotham made the first Algorithm With Fuzzy Logic for DoS/DDoS Mitigation video game - Pong. It was a really basic game with the on SDN Networks’ [1] where the authors propose a sys- aim to bounce a ball past the opponent. Since then games tem to faster detect possible attacks based on the de- began to appear rapidly, starting quite simple but getting nial of service (DoS) using the anomaly detection and more and more complex parallel to the advances in the identification provided by an HWDS system with an au- technology available. Suddenly a need for something tonomous decision-making model based on game theory. new appeared - something that would make games more Another worth mentioning paper is ’A fuzzy logic and challenging and fun to play. Conveniently around this game theory-based adaptive approach for securing oppor- time, artificial intelligence came in handy, giving game tunistic networks against black hole attacks’ [2] where a developers a lot more room for creativity. Artificial in- security protocol named FuzzyPT is proposed to combat telligence started to become an integral part of video blackhole attacks in OppNets. Fuzziness aids the system games in the 1970s, with the first wellknown game con- in being adaptive by modeling the single nodes as neither taining AI - Space Invaders. Code of this game analyses benign nor malicious but rather judging a set of nodes player’s movement and increases difficulty as time goes based on relationships between different parameters, re- on. Another famous game with an AI onboard is Pac- sulting in a decreased number of false positives and false Man, where different ghosts have different approaches negatives. Again in [3], the fuzzy-entropy-based game for hunting the main character. Today AI in games is far was proposed by the analysis from the perspective of more advanced and takes to account much more variables. uncertainty. Similarly, a soft matrix game was shown in For example in racing games, AI is aware of the track [4], where another approach of hesitant fuzzy MCDM pattern as well as weight distribution and powerband of was used. However, fuzzy logic can be used not only in the car. Using this and the knowledge about defensive, the Internet of Things - in ’An adaptive self-organizing offensive, or balanced driving it can be a really tough fuzzy logic controller in a serious game for motor impair- opponent. In our project we decided to focus on one task: ment rehabilitation’ [5] the authors present ReHabGame, avoiding obstacles. Even though it might sound quite a game that can be easily used by patients and thera- simple, a lot of work had to be put into the code, yet we pists to assess and enhance sensorimotor performance did not fully achieve it. and also help to increase the activities in the daily lives of patients. The different quantities of movement pro- ICYRIME 2021 @ International Conference of Yearly Reports on vide fuzzy input from which crisp output is determined Informatics Mathematics and Engineering, online, July 9, 2021 and used to generate an appropriate rehabilitation game " justwal728@student.polsl.pl (J. Walotek) © 2021 Copyright for this paper by its authors. Use permitted under Creative level, making it a personalized, autonomously learned Commons License Attribution 4.0 International (CC BY 4.0). CEUR Workshop Proceedings http://ceur-ws.org ISSN 1613-0073 CEUR Workshop Proceedings (CEUR-WS.org) rehabilitation program. The latest years brought many 77 Justyna Walotek et al. CEUR Workshop Proceedings 77–84 interesting approaches to game theory and its applica- tions. For instance, virtual reality [6] was improved by using the convolutional neural networks and many differ- ent sensors for increasing the inversion in virtual reality. Machine learning solutions was also applied in many dif- ferent real scenario [[7, 10]. Games are used for different purposes, not only in entertainment but also in educa- tional areas. It was shown in [14, 16, 17, 12, 13], where fuzzy logic was analyzed in mobile games for students. Fuzzy logic as other areas of artificial intelligence can be Figure 1: Linguistic values depending on the distance mea- used in many areas [18, 20, 21]. sured 3. Fuzzy logic and the power of words One of the biggest differences between humans and com- puters is the ability to use abstract concepts to describe reality. We can say for example that something is small, short, blue or that it is far away from us. While doing it, we do not assign a certain value to it, like 2cm3 2 seconds, #007EFF or 100km. Instead, we perceive those values as a scale - a certain range of values can be assigned to a certain word. For example, one person can perceive some- thing as light when it weighs up to 2 kg, while another person may think that 5kg is still light and their scale Figure 2: Measuring the distance using raycast in Unity for the definition of the word ’light’ is more like 1-6kg because something under 1kg is perceived as ’very light’. But how does it apply to computers? Computers do not 2. the number of input values determines the count understand abstract concepts, they use exact values to of rules - having 7 input values and 3 possible lin- describe things. While in some cases it is the preferred guistic values gives us 3 7 possible situations and approach, in others it might be a real issue. Imagine us- all of them need a rule. Decreasing the number of ing a brake only when the distance between the driven input values to 3 the count of rules changes to 33 car and the car in front of it is smaller than 1.5m and , making it possible to manage and less resource in addition always using only the full force of the brake. consuming. Standing in traffic would be unbearable, would it not? One of the solutions for this type of issue is using fuzzy Every input value needs to be fuzzified - a linguistic logic. Fuzzy logic is a type of logic, where input contain- value is being assigned depending on the range the input ing exact values is converted into linguistic values called value suits best. antecedents, which can be then processed using rules, The mathematical equation (eq. 1) used for fuzzyfying giving us different linguistic values describing the output the input: called consequents, which are then defuzzyfied giving us new exact values for the final output. This may sound difficult or complicated, but actually, it is not that hard to achieve. Using the example of our project, we will try to show this process as simply as possible. Our car mea- (1) sures the distance to the nearest obstacle in 7 directions:In the eq. 1 the values a bvand c depend on the lin- to the front, 15∘ , 30∘ and 75∘ to the left, similarly to the guistic value the equation is used for. If we write those right. Next, those falues are being used to calculate thevalues as linguisticValue=[a,b,c] then: weighted average for 3 directions: left, front, and right. red=[0, 0, 5] It is done because of two reasons: yellow=[3,6,10] 1. we decided to have just two output values - hori- green=[8, 12, 100] zontal and vertical - which determine if the car This means, that every input value has 3 new values goes forward and if it turns in either direction, assigned, one for each linguistic value, so for example input=5 would give us 0 for red, 0.6 for yellow, and 0 for 78 Justyna Walotek et al. CEUR Workshop Proceedings 77–84 Figure 4: Figure 5: Finally, as we described earlier we compute the final Figure 3: rules output - horizontal and vertical values. Later it came to our attention, that those values needed to be slightly modified, so we added some more factors to the multipli- green. When all of the input values have those linguistic cation (Fig.5) values assigned, we can move on to the rules. When all This certainly is not the most optimal way to do it, but of the input values have those linguistic values assigned, for our needs was good enough we can move on to the rule shown in Fig. 3 As we said before, we need 27 rules to cover every possible situation that may occur. Every rule consists 4. Raycast in Unity of linguistic values for the input and linguistic values Raycast is a technology that allows you to determine the for the output. Using values of how well the inputs fit distance of a casting point projecting from a mesh that the red, yellow and green range, rule values are being has crossed its path (Of course, if this mesh has a collider). calculated simply by multiplying the values assigned to In order to properly project a raycast, it is necessary to the linguistic values in the rule. For example rule a con- provide it with a starting point and a direction relative sists of all red, so the rule value will be: 𝑟𝑢𝑙𝑒𝑉 𝑎𝑙𝑢𝑒 = to the object associated with it, for example, a car or a 𝑙𝑒𝑓 𝑡𝑅𝑒𝑑𝑉 𝑎𝑙𝑢𝑒 * 𝑓 𝑟𝑜𝑛𝑡𝑅𝑒𝑑𝑉 𝑎𝑙𝑢𝑒 * 𝑟𝑖𝑔𝑡ℎ𝑅𝑒𝑑𝑉 𝑎𝑙𝑢𝑒 rifle. This technology is successfully used in fps and RPG This way we determine which rule is the most accurate games to detect whether the target of a specific character for the given input - we simply take the one with the is in its field of view and is not obstructed by anything highest rule value. In our case the simplest way to de- (for example, enemies looking for the main character). In fuzzyfy was to assign certain values to the consequent the case of the former, raycast is also very often used to values and compute the output by multiplying the rule’s determine where the shot fired from the weapon will hit. consequent and its ruleValue (Fig.4) Although this method is slowly being abandoned as it is 79 Justyna Walotek et al. CEUR Workshop Proceedings 77–84 Figure 7: to create a track. Our first idea was simple: pick any premade area. This could be enough if the car would be driven by a user, but not for AI because a standard track would not give the AI any information about its’ Figure 6: Flowchart of the AI’s algorythm boundaries. The next guess was to upgrade the course for our car, upgraded version should have some kind of barriers to create a path to the finish line. This plan was not realistic enough - in the real world, the projectile’s quickly discarded and the next concept was to create a flight path is not a perfectly straight line and additionally, track using prepared parts like turns or u-turns. The its speed is limited, so where the raycast would register biggest issue with this solution was the fact, that if the a hit, the real bullet could miss the target if it is mov- substrate was not perfectly flat, AI did not work properly. ing. Therefore, the gaming industry is slowly starting to The last idea, other than forcing our car to fly, was to use a different method, which is to generate additional create a route ourselves from scratch. We decided on bullets with a given initial velocity and mass. Of course, recreating one of the most famous auto and motorcycle however, there are exceptions where the raycast has an raceways: Laguna Seca Raceway. To better suit our needs advantage over simulated ballistics. One such exception it was shrunk (to spend less time on every lap) and the is dynamic fps games with relatively small maps. After driving surface was increased to make the turns simpler. all, the ballistics and the velocity of a projectile at short The base structure of the road was made in Blender. Due distances are not that significant, and raycast consumes to problems with mesh colliders, the walls are reinforced much fewer hardware resources. This is because it is only with additional blocks made from basic cubes in Unity. active for one frame (short hit test immediately after the This way the raycast could finally work properly. There shot), while the position of the bullet with active ballis- are two turns that turned out to be difficult both for AI tics must be counted until the hit and, additionally, many and the players. such bullets can appear in the memory at the same time. The left one (a) looks simple at first glance but with In our case, raycast was the best option for gathering data a long straight road before the turn where the car can about the surroundings, because it is a simple and fast drastically accelerate, it was enough to make the car way to do it. When driving a car we need as little delay unable to pass through without hitting the wall. The right as possible, so the simpler and less resourceconsuming one (b) is a u-turn which requires some skill from the method the better. players to drive without a collision, so it was too difficult To make our car move, we needed a simple script and for AI regardless of the car’s speed when entering the a bit of Unity’s physics. We added round colliders into turn. The title of this paragraph still seems to be unrelated the car’s wheels and we by rotating them we move the to the topic, so let us explain. Accidentally we recreated car. one of the scenes from the series ’Initial D’, because the The car also has a rigidbody attribute, so the Unity’s car one of the members of our group picked from Unity physics engine can apply gravity to it and detect colli- Asset Store is a model of Toyota AE86 (main character’s sions. car) and the turn (a) was also difficult for the characters It is very unlikely for cars to float in space so we needed of this series. Unfortunately AI we created does not drift 80 Justyna Walotek et al. CEUR Workshop Proceedings 77–84 Figure 8: Car with the rigidbody attribute in Unity Figure 10: Our version adjusted to better suit our needs in Unity Figure 11: Model of the car in the Asset Store some of the values are colored, here are their meanings: Figure 9: Original Laguna Seca track - layout painted by • yellow - the best time achieved on those settings, Alexander Jones • orange - the car was really close to hitting one of the walls • red - the car nudged the wall but it did not stop very well. At the moment of writing this article, the it for long, model is no longer available, because the package has • purple - the car hit the wall and it did have some been deprecated from the Asset Store. trouble continuing the lap 5. Experiments With this knowledge we focused on selecting the fric- tion and drag parameters for the physics of the vehicle In order to optimize the vehicle so that it would lap the wheels. Until the expected results were obtained, we track in the best time possible and without collisions, e modified both the sliding and the static friction. Op- had to conduct a series of tests consisting of changing timal effects were acquired only when the extreme of selected parameters in Unity and checking which config- static friction was about twice as high as the sliding urations would give the best results. Before conducting friction. We also needed to adjust the weights of the more constructive tests, we began with random parame- wheels and of the car itself to more reasonable amounts. ters and started testing how MaxTorque and the wheel WheelFrictionCurve is used by the WheelCollider to drive impact a car’s ability to maneuver (simultaneously describe the friction properties of the wheel tire. The we were trying to find room for the code’s improvement). curve takes a measure of tire slip as an input and gives We found that as the expected time needed to lap the a force as output. The curve is approximated by a two- track decreased as MaxTorque increased until the point, piece spline. The first section goes from (0,0) to (ex- where the car could no longer respond fast enough and tremumSlip,extremumValue), at which point the curve’s started to hit a wall. Some of the values stayed unmea- tangent is zero. The second section goes from (extremum- sured because we found them insignificant. In the table Slip,extremumValue) to (asymptoteSlip,asymptoteValue), 81 Justyna Walotek et al. CEUR Workshop Proceedings 77–84 Figure 13: Time per lap depending on MaxTorque value for all wheel drives Figure 12: Starting variables in car’s attributes in Unity Figure 14: Wheel settings after adjusting in Unity where curve’s tangent is again zero. Wheel collider com- relation to the center of mass of the wheel with a radius putes friction separately from the rest of the physics of 30 centimeters. As a result, we achieved not only the engine, using a slip based friction lack of the vehicle overturning but also the curb weight model. It separates the overall friction force into a and the engine torque was significantly reduced. After ”forwards” component (in the direction of rolling, and establishing which friction and drag parameters were the responsible for acceleration and braking) and ”sideways” most effective, we moved onto the next text in which we component (orthogonal to rolling, responsible for keep- wanted to see how changing the maximum torque param- ing the car-oriented). Tire friction is described separately eters will affect the time the car will finish the race. The in these directions using WheelCollider.forwardFriction table below shows the dependence of max torque on time. and WheelCollider.sidewaysFriction. In both directions Changing max torque values from 500 to 1000 in steps it is first determined how much the tire is slipping. Then of 100 with the Front Wheel Drive. Then we decided the slip value is used to find out the tire force exerted on to check which drivetrain setting would be the most ef- the contact. Finally, after making many adjustments to fective for the fastest track completion. In this test, the the parameters, we came to the conclusion that the best maximum torque remained 800 for both the front-wheel- results were obtained when both of the drag parameters drive and the rear-wheel drive, but 400 for the all-wheel were set to the minimum. Then the center of friction drive. It was measured for 3 attempts. The table below force application acting on the wheels was lowered in shows the dependence of different drive layouts on time 82 Justyna Walotek et al. CEUR Workshop Proceedings 77–84 Figure 15: WheelFriction graph Table 3 Time needed for a different wheel drive it can be seen that in order to obtain a collision-free test with the fastest possible time to complete the race, the following parameters turned out to be the best choice: • the extreme of static friction about twice as high as the sliding friction • both of the drag parameters set to the minimum • the center of friction force application acting on the wheels lowered in relation to the center of mass of the wheel • front-wheel drive • max torque value of 800 6. Conclusion In conclusion, AI works properly up to a certain velocity. However, after reaching higher speeds, it is not able to respond fast enough, which results in a collision with the wall. The car is also not capable of coping with an obstacle placed closely in front of it, falling into the path selection loop of going slightly forwards and slightly Table 1 backward. Not surprisingly, when it comes to checking Obtained results whether the player or artificial intelligence is doing a better job, as long as the best technique to achieve the best time will be drifting, AI will fall far behind the play- ers or even not finish the lap. Despite the difficulties Table 2 encountered, the following situation was achieved: the Max torque value and obtained time car, regardless of its starting point, is able to move and complete the given track without major issues. However, the results achieved by a human driver are still noticeably To summarize, by setting the max torque value to 800, better than those achieved by artificial intelligence. Ulti- the best time to complete the track was achieved. As mately, the chosen goal was accomplished because the for the drivetrain, the front wheel drive turned out to car can indeed successfully drive without human inter- be the best choice, also achieving the fastest completion vention and without the need to be trained beforehand. times. Taking into consideration all the tests performed, 83 Justyna Walotek et al. CEUR Workshop Proceedings 77–84 References 4_3. [12] A. Ozdemir, K. F. Balbal, Fuzzy logic based per- [1] M. V. De Assis, A. H. Hamamoto, T. Abrao, M. L. formance analysis of educational mobile game for Proenca, A game theoretical based system using engineering students, Computer Applications in holt-winters and genetic algorithm with fuzzy logic Engineering Education 28 (2020) 1536–1548. for dos/ddos mitigation on sdn networks, IEEE Ac- [13] C. Troussas, A. Krouska, C. Sgouropoulou, Collabo- cess 5 (2017) 9485–9496. ration and fuzzy-modeled personalization for mo- [2] A. Chhabra, V. Vashishth, D. K. Sharma, A fuzzy bile game-based learning in higher education, Com- logic and game theory based adaptive approach for puters & Education 144 (2020) 103698. securing opportunistic networks against black hole [14] G. Capizzi, G. Lo Sciuto, C. Napoli, E., Tramontana, attacks, International Journal of Communication A multithread nested neural network architecture Systems 31 (2018) e3487. to model surface plasmon polaritons propagation [3] Q. Zhang, M. Gao, F. Zhao, G. Wang, Fuzzy- (2016) Micromachines, 7 (7), art. no. 110 entropybased game theoretic shadowed sets: A [15] De Magistris G., Russo S., Roma P., Starczewski novel game perspective from uncertainty, IEEE J.T., Napoli C., An Explainable Fake News Detec- Transactions on Fuzzy Systems (2020). tor Based on Named Entity Recognition and Stance [4] J. Jana, S. Kumar Roy, Soft matrix game: A hesi- Classification Applied to COVID-19 (2022) Informa- tant fuzzy mcdm approach, American Journal of tion, 13 (3), art. no. 137, DOI: 10.3390/info13030137. Mathematical and Management Sciences 40 (2021) [16] G. Lo Sciuto, G. Capizzi, S. Coco, R. Shikler, Geo- 107–119. metric shape optimization of organic solar cells for [5] S. S. Esfahlani, S. Cirstea, A. Sanaei, G. Wilson, efficiency enhancement by neural networks (2017) An adaptive self-organizing fuzzy logic controller Lecture Notes in Mechanical Engineering. in a serious game for motor impairment rehabil- [17] G. Capizzi, F. Bonanno, C. Napoli, Hybrid neural itation, in: 2017 IEEE 26th International Sympo- networks architectures for SOC and voltage predic- sium on Industrial Electronics (ISIE), IEEE, 2017, pp. tion of new generation batteries storage (2011) 3rd 1311–1318. International Conference on Clean Electrical Power: [6] D. Polap, K. Kesik, A. Winnicka, M. Wozniak, Renewable Energy Resources Impact, ICCEP 2011, Strengthening the perception of the virtual worlds art. no. 6036301, pp. 341 - 344 in a virtual reality environment, ISA transactions [18] D. Polap, M. Wozniak, Meta-heuristic as manager in 102 (2020) 397–406. federated learning approaches for image processing [7] X. Shi, A. Emrouznejad, M. Jin, F. Yang, A new purposes, Applied Soft Computing (2021) 107872. parallel fuzzy data envelopment analysis model for [19] Połap D., Wózniak M., Napoli C., Tramontana E., Is parallel systems with two components based on Swarm Intelligence Able to Create Mazes? (2015) In- stackelberg game theory, Fuzzy Optimization and ternational Journal of Electronics and Telecommu- Decision Making 19 (2020) 311–332. nications, 61 (4), pp. 305 - 310, DOI: 10.1515/eletel- [8] Brandizzi N., Bianco V., Castro G., Russo S., Wa- 2015-0039. jda A., Automatic RGB Inference Based on Facial [20] Cardarilli, G.C., Nunzio, L.D., Fazzolari, R., Panella, Emotion Recognition (2021) CEUR Workshop Pro- M., Re, M., Rosato, A., Spano, S., A Parallel Hard- ceedings, 3092, pp. 66 - 74. ware Implementation for 2-D Hierarchical Cluster- [9] Brociek R., Magistris G.D., Cardia F., Coppa F., ing Based on Fuzzy Logic (2021) IEEE Transactions Russo S., Contagion Prevention of COVID-19 by on Circuits and Systems II: Express Briefs, 68 (4), means of Touch Detection for Retail Stores (2021) art. no. 9234481, pp. 1428-1432. CEUR Workshop Proceedings, 3092, pp. 89 - 94 [21] K. Bhattacharya, S. K. De, A robust two layer green [10] D. Połap, M. Wlodarczyk-Sielicka, N. Wawrzyniak, supply chain modelling under performance based Automatic ship classification for a riverside mon- fuzzy game theoretic approach, Computers & In- itoring system using a cascade of artificial intelli- dustrial Engineering 152 (2021) 10700 gence techniques including penalties and rewards, ISA transactions (2021). [11] Capizzi G., Napoli C., Paternò L., An innovative hybrid neuro-wavelet method for reconstruction of missing data in astronomical photometric surveys (2012) Lecture Notes in Computer Science (includ- ing subseries Lecture Notes in Artificial Intelligence and Lecture Notes in Bioinformatics), 7267 LNAI (PART 1), pp. 21 - 29, DOI: 10.1007/978-3-642-29347- 84