bilago

GTA5 - Spawn Vehicles on dirt roads

Aug 5th, 2015
1,251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 15.76 KB | None | 0 0
  1. //v1.2.2 (8/6/2015 9:11AM)
  2. //Script by Bilago
  3. //Original VB script written by 5mith
  4. //https://www.gta5-mods.com/scripts/off-road-traffic
  5.  
  6. //changes from 1.2.1 -> 1.2.2
  7. //Minor code change to prevent issues adding more locations
  8. //overhaul on vehicle/pedestrian generation
  9. //Prevents vehicles from spawning in front of a user.
  10. //
  11. //changes from 1.2 -> 1.2.1
  12. //Fixed a typo that may cause the script to no longer function
  13. //
  14. //changes from 1.1 -> 1.2
  15. //Added 3 more vehicles (Jeeps) Thanks tall70
  16. //Added BF Injection and Dune vehicles Thanks JWillMac51!
  17. //Removed hard coded distance and use per Location distance for check
  18. //Made the tick rate lower for driving faster than 40f (was 3 seconds now is 2)
  19. //Added a check to make sure the pedestrian spawned before trying to give weapons
  20. //Added configurable setting for spawn speed when driving fast and slow
  21.  
  22. using System;
  23. using System.Collections;
  24. using System.Collections.Generic;
  25. using GTA;
  26. using GTA.Math;
  27. using GTA.Native;
  28. using System.Drawing;
  29.  
  30. public class Traffic : Script
  31. {
  32.     /// <summary>
  33.     /// Change this to increase/decrease the delay between spawning vehicles when driving
  34.     /// This is measured in seconds
  35.     /// SpawnSpeedDrivingFast is used when going over 40MPH
  36.     /// SpawnSpeedDrivingSlow is used when going less than 40MPH.
  37.     /// </summary>
  38.     private int SpawnSpeedDrivingFast = 2; //seconds
  39.     private int SpawnSpeedDrivingSlow = 3; //seconds
  40.  
  41.     /// <summary>
  42.     /// List of vehicles to spawn randomly
  43.     /// </summary>
  44.     private List<string> GeneralVehicles = new List<string>()
  45.     {
  46.            "granger", "sanchez2", "bmx", "tractor", "sanchez", "landstalker", "rebel", "bodhi", "bjxl", "blazer", "bobcatxl", "asea", "rancherxl", "sandking",
  47.            "patriot", "blazer3", "asterope", "gburrito2", "scorcher", "brawler", "fugitive", "baller", "enduro", "rhapsody", "youga",
  48.            "serrano", "sandking2", "dukes", "sheriff", "sheriff2", "fbi2", "pranger", "cavalcade", "dloader", "mesa", "mesa2", "mesa3", "bfinjection", "dune"
  49.     };
  50.  
  51.     /// <summary>
  52.     /// List of pedestrian types you want to spawn (leave blank to spawn any random pedestrians)
  53.     /// Putting pedestrians in this list will only spawn from this list!
  54.     /// </summary>
  55.     private List<string> GeneralDrivers = new List<string>()
  56.     {
  57.         //currently blank so all pedestrians have a chance to spawn
  58.     };
  59.  
  60.     /// <summary>
  61.     /// List of Military Only Vehicles
  62.     /// </summary>
  63.     private List<string> MarineVehicles = new List<string>()
  64.     {
  65.         "crusader", "barracks", "barracks2", "barracks3", "insurgent", "insurgent2", "technical", "sanchez"
  66.     };
  67.  
  68.     /// <summary>
  69.     /// List of Marines to spawn randomly
  70.     /// </summary>
  71.     private List<string> MarineDrivers = new List<string>()
  72.     {
  73.         "S_M_M_Marine_01"
  74.     };
  75.  
  76.     /// <summary>
  77.     /// List of Police Only Vehicles
  78.     /// </summary>
  79.     private List<string> PoliceVehicles = new List<string>()
  80.     {
  81.        "sheriff", "sheriff2", "fbi2", "pranger"
  82.     };
  83.  
  84.     /// <summary>
  85.     /// List of Police officers to spawn randomly if a police vehicle is chosen
  86.     /// </summary>
  87.     private List<string> PoliceDrivers = new List<string>()
  88.     {
  89.         "S_M_Y_Ranger_01", "S_M_Y_Sheriff_01"
  90.     };
  91.  
  92.     /// <summary>
  93.     /// Weapons to give randomly to regular Police officers
  94.     /// </summary>
  95.     private List<WeaponHash> policeWeapons = new List<WeaponHash>()
  96.     {
  97.         WeaponHash.Pistol, WeaponHash.StunGun, WeaponHash.VintagePistol, WeaponHash.Nightstick, WeaponHash.Pistol50, WeaponHash.HeavyShotgun, WeaponHash.SNSPistol
  98.     };
  99.  
  100.     /// <summary>
  101.     /// Weapons to give randomly to Marines
  102.     /// </summary>
  103.     private List<WeaponHash> marinesWeapons = new List<WeaponHash>()
  104.     {
  105.         WeaponHash.SMG, WeaponHash.AdvancedRifle, WeaponHash.SpecialCarbine, WeaponHash.HeavyShotgun, WeaponHash.APPistol
  106.     };
  107.  
  108.     /// <summary>
  109.     /// Weapons to give randomly to pedestrians
  110.     /// Multiple Unarmed entries increases chances the pedestrian is weaponless
  111.     /// </summary>
  112.     private List<WeaponHash> pedestrianWeapons = new List<WeaponHash>()
  113.     {
  114.         WeaponHash.Bat, WeaponHash.Pistol, WeaponHash.Knife, WeaponHash.Crowbar, WeaponHash.Unarmed, WeaponHash.Unarmed, WeaponHash.Unarmed, WeaponHash.Unarmed
  115.     };
  116.  
  117.     /// <summary>
  118.     /// Seats to place pedestrians when spawning more than one
  119.     /// </summary>
  120.     private List<VehicleSeat> availableSeats = new List<VehicleSeat>() {
  121.         VehicleSeat.Driver//, VehicleSeat.RightFront        
  122.     };
  123.  
  124.  
  125.     //Entry Function
  126.     public Traffic()
  127.     {  
  128.         setupLocations();
  129.  
  130.         //Converting seconds to milliseconds
  131.         SpawnSpeedDrivingFast = SpawnSpeedDrivingFast * 1000;
  132.         SpawnSpeedDrivingSlow = SpawnSpeedDrivingSlow * 1000;
  133.  
  134.         Tick += general_tick;
  135.         this.Interval = 8000;
  136.     }
  137.  
  138.     //Per tick function
  139.     private void general_tick(object sender, EventArgs e)
  140.     {
  141.         bool atLocation = false;
  142.         //Iterate Through all Locations stored
  143.         for (int i = 0; i < Locations.Count; i++)
  144.         {
  145.             if (Game.Player.Character.IsInRangeOf(Locations[i].Location, Locations[i].Distance))
  146.             {
  147.                 atLocation = true;
  148.                 //lets spawn a vehicle
  149.                 SpawnRandomVehicle(Locations[i]);
  150.  
  151.                 //if the player is driving and is going over 40, lets increase the script speed
  152.                 if (Game.Player.Character.IsInVehicle())
  153.                 {
  154.                     if (Game.Player.Character.CurrentVehicle.Speed > 40f)
  155.                         changeInterval(SpawnSpeedDrivingFast);
  156.                     else if (Game.Player.Character.CurrentVehicle.Speed < 5f)
  157.                         changeInterval(8000);
  158.                     else
  159.                         changeInterval(SpawnSpeedDrivingSlow);
  160.                 }
  161.                 else
  162.                     changeInterval(8000);
  163.  
  164.                 break;
  165.             }
  166.         }
  167.         //if we get here that means we're not near any specified location, let's increase the interval delay
  168.         if(!atLocation)
  169.             changeInterval(8000);
  170.     }
  171.  
  172.     /// <summary>
  173.     /// Changes the tick interval of this mod
  174.     /// </summary>
  175.     /// <param name="interval">delay between ticks (milliseconds)</param>
  176.     private void changeInterval(int interval)
  177.     {
  178.         if (this.Interval != interval)
  179.             this.Interval = interval;
  180.     }
  181.  
  182.     private string log = "OffRoad-TrafficERRORS.log";
  183.     private Vehicle v;
  184.     private Ped d;
  185.     private static Random r = new Random();
  186.     private List<LocationInfo> Locations = new List<LocationInfo>();
  187.  
  188.  
  189.     /// <summary>
  190.     /// Stores the spawn locations
  191.     /// </summary>
  192.     public class LocationInfo
  193.     {
  194.         public string ID { get; set; }
  195.         public Vector3 Location;
  196.         public List<string> Vehicles { get; set; }
  197.         public List<string> DriverTypes = new List<string>();
  198.         public List<WeaponHash> Weapons { get; set; }
  199.         public float Distance { get; set; }
  200.     }
  201.  
  202.     /// <summary>
  203.     /// This sets up all the spawn location information, should only run once in the startup method
  204.     /// </summary>
  205.     private void setupLocations()
  206.     {
  207.         LocationInfo Zancudo = new LocationInfo()
  208.         {
  209.             ID = "Zancudo",
  210.             Location = new Vector3(-1524.5f, 3402.34f, 100f),
  211.             DriverTypes = MarineDrivers,
  212.             Vehicles = MarineVehicles,
  213.             Weapons = marinesWeapons,
  214.             Distance = 1100f
  215.         };
  216.         Locations.Add(Zancudo);
  217.  
  218.         LocationInfo Chapparral = new LocationInfo()
  219.         {
  220.             ID = "Chapparral",
  221.             Location = new Vector3(-184.18f, 2347.42f, 102f),
  222.             DriverTypes = GeneralDrivers,
  223.             Vehicles = GeneralVehicles,
  224.             Weapons = pedestrianWeapons,
  225.             Distance = 1000f
  226.         };        
  227.         Locations.Add(Chapparral);
  228.  
  229.  
  230.         LocationInfo Paleto = new LocationInfo()
  231.         {
  232.             ID = "Paleto",
  233.             Location = new Vector3(-617.55f, 5844.59f, 24f),
  234.             DriverTypes = GeneralDrivers,
  235.             Vehicles = GeneralVehicles,
  236.             Weapons = pedestrianWeapons,
  237.             Distance = 1000f
  238.         };        
  239.         Locations.Add(Paleto);
  240.  
  241.         LocationInfo NatPark = new LocationInfo()
  242.         {
  243.             ID = "NatPark",
  244.             Location = new Vector3(-947.53f, 4615.99f, 240f),
  245.             DriverTypes = GeneralDrivers,
  246.             Vehicles = GeneralVehicles,
  247.             Weapons = pedestrianWeapons,
  248.             Distance = 1000f
  249.         };        
  250.         Locations.Add(NatPark);
  251.  
  252.         LocationInfo Dam = new LocationInfo()
  253.         {
  254.             ID = "Dam",
  255.             Location = new Vector3(1862.24f, 159.23f, 176.15f),
  256.             DriverTypes = GeneralDrivers,
  257.             Vehicles = GeneralVehicles,
  258.             Weapons = pedestrianWeapons,
  259.             Distance = 600f
  260.         };      
  261.         Locations.Add(Dam);
  262.  
  263.         LocationInfo Molinos = new LocationInfo()
  264.         {
  265.             ID = "Molinos",
  266.             Location = new Vector3(2293.53f, 1938.54f, 127.58f),
  267.             DriverTypes = GeneralDrivers,
  268.             Vehicles = GeneralVehicles,
  269.             Weapons = pedestrianWeapons,
  270.             Distance = 600f
  271.         };        
  272.         Locations.Add(Molinos);
  273.     }
  274.  
  275.     /// <summary>
  276.     /// This spawns a random vehicle based on the location data
  277.     /// </summary>
  278.     /// <param name="location">Where the player is currently close to</param>
  279.     private void SpawnRandomVehicle(LocationInfo location)
  280.     {
  281.         if (location.Vehicles.Count == 0)
  282.         {
  283.             writeLog("Vehicle list specified is empty.. cannot spawn");
  284.             return;
  285.         }
  286.         string Vehicle = location.Vehicles[GetRandomNumber(location.Vehicles.Count)];
  287.         List<string> drivers = new List<string>();
  288.         List<WeaponHash> weaponList = new List<WeaponHash>();
  289.         bool isPedestrian = false;
  290.  
  291.         if (PoliceVehicles.Contains(Vehicle))
  292.         {
  293.             drivers = PoliceDrivers;
  294.             weaponList = policeWeapons;
  295.         }
  296.         else
  297.         {
  298.             isPedestrian = !MarineVehicles.Contains(Vehicle);
  299.             drivers = location.DriverTypes;
  300.             weaponList = location.Weapons;
  301.         }
  302.  
  303.         createVehicle(Vehicle, drivers, weaponList, isPedestrian);
  304.     }
  305.    
  306.     /// <summary>
  307.     /// Creates a vehicle with the specified vehicle name and driver
  308.     /// </summary>
  309.     /// <param name="Vehicle">The type of vehicle to spawn</param>
  310.     /// <param name="driver">the type of driver to spawn. Empty string will create a random pedestrian</param>
  311.     private void createVehicle(string Vehicle, List<string> drivers, List<WeaponHash> weapons, bool isPedestrian)
  312.     {
  313.         try
  314.         {
  315.             //spawns a vehicle with a random distance between 200 and 500
  316.             v = World.CreateVehicle(Vehicle, Game.Player.Character.Position.Around((float)GetRandomNumber(150, 300)));
  317.  
  318.             if (v == null)
  319.             {
  320.                 writeLog(string.Format("{0} is not a valid vehicle", Vehicle));
  321.                 return;
  322.             }
  323.            
  324.             //This helps but makes traffic way too sparse for the amount that's spawned.
  325.             //while (!v.IsOccluded)
  326.             //{
  327.             //    v.Position = Game.Player.Character.Position.Around(90);
  328.             //    v.PlaceOnNextStreet();
  329.             //    Wait(10);
  330.             //}
  331.            
  332.             for (int i = 0; i < availableSeats.Count; i++)
  333.             {
  334.                 VehicleSeat seat = availableSeats[i];
  335.                 int rand =0;
  336.                 if (v.IsSeatFree(seat))
  337.                 {
  338.                     if (drivers.Count == 0)
  339.                         d = v.CreateRandomPedOnSeat(seat);
  340.                     else
  341.                     {
  342.                         rand = GetRandomNumber(drivers.Count);
  343.                         d = v.CreatePedOnSeat(seat, drivers[rand]);
  344.                     }
  345.  
  346.                     if (d == null)
  347.                     {
  348.                         writeLog("An Invalid Pedestrian Type was used! Check your spawn list!");
  349.                         writeLog(string.Format("Random number :{0}  List value: {1}", rand, drivers[rand]));
  350.                         v.MarkAsNoLongerNeeded();
  351.                         v.Delete();
  352.                         return;
  353.                     }
  354.                     d.Task.WarpIntoVehicle(v, seat);
  355.  
  356.                     //Lets generate two weapons for the NPC we're about to create
  357.                     WeaponHash weaponSlot0 = WeaponHash.Unarmed;
  358.                     WeaponHash weaponSlot1 = WeaponHash.Unarmed;
  359.                     GenerateWeaponSlots(ref isPedestrian, ref weapons, ref weaponSlot0, ref weaponSlot1);
  360.                     d.Weapons.Give(weaponSlot0, 1000, true, true);
  361.                     d.Weapons.Give(weaponSlot1, 1000, true, true);
  362.  
  363.                     d.MarkAsNoLongerNeeded();
  364.                 }
  365.             }
  366.             v.MarkAsNoLongerNeeded();
  367.  
  368.             //Lets make sure someone made it into the driver seat.. if not lets delete the car
  369.             if (v.IsSeatFree(VehicleSeat.Driver))
  370.                 v.Delete();
  371.             //else
  372.             //    writeLog(string.Format("Vehicle {0} created with pedestrian {1}", v.DisplayName, d.Handle));
  373.         }
  374.         catch
  375.         {
  376.            writeLog("ERROR Creating vehicle!");
  377.             return;
  378.         }        
  379.     }
  380.  
  381.     /// <summary>
  382.     /// This will generate two weapons
  383.     /// </summary>
  384.     /// <param name="isPedestrian">if this is true, there is a 50% chance that they will not be part of the 'weapon lottery'</param>
  385.     /// <param name="weapons">the list of weapons to choose from</param>
  386.     /// <param name="a">weapon 1</param>
  387.     /// <param name="b">weapon 2</param>
  388.     private void GenerateWeaponSlots(ref bool isPedestrian, ref List<WeaponHash> weapons, ref WeaponHash a, ref WeaponHash b)
  389.     {
  390.         try
  391.         {
  392.             if (weapons.Count == 0)
  393.                 return;
  394.             if (isPedestrian)
  395.             {
  396.                 if (r.NextDouble() > 0.5)
  397.                     return;
  398.             }
  399.  
  400.             a = weapons[GetRandomNumber(weapons.Count)];
  401.             b = weapons[GetRandomNumber(weapons.Count)];
  402.         }
  403.         catch
  404.         {
  405.             a = WeaponHash.Unarmed;
  406.             b = WeaponHash.Unarmed;
  407.         }
  408.     }
  409.    
  410.     /// <summary>
  411.     /// Generates a random number
  412.     /// </summary>
  413.     /// <param name="max">The exclusive maximum of the range</param>
  414.     /// <returns>a number from 0 to (max - 1)</returns>
  415.     private int GetRandomNumber(int max)
  416.     {
  417.         return GetRandomNumber(0, max);
  418.     }
  419.  
  420.     /// <summary>
  421.     /// Generates a random number
  422.     /// </summary>
  423.     /// <param name="min">The inclusive minimum of the range</param>
  424.     /// <param name="max">The exclusive maximum of the range</param>
  425.     /// <returns>a number from min to (max - 1) </returns>
  426.     private int GetRandomNumber(int min, int max)
  427.     {
  428.         //dont bother getting a random number if the max is 1
  429.         if (max == 1)
  430.             return 0;
  431.  
  432.         try
  433.         {
  434.             return r.Next(0, max);
  435.         }
  436.         catch
  437.         {
  438.             return 0;
  439.         }
  440.     }
  441.  
  442.     private void writeLog(string text)
  443.     {      
  444.  
  445.         string message = string.Empty;
  446.         if (!string.IsNullOrEmpty(text))
  447.             message = string.Format("[{0}] - {1}", DateTime.Now, text);
  448.  
  449.         using (System.IO.StreamWriter write = new System.IO.StreamWriter(log, true))
  450.         {
  451.             write.WriteLine(message);
  452.         }
  453.         //System.IO.File.AppendAllText(log, message);
  454.        
  455.     }
  456. }
Advertisement
Add Comment
Please, Sign In to add comment