Hello I'm having some problems with a callout making I don't know if anyone here can help me but I'll try asking anyway.
Information
I'm making a CalloutPack for a game called Grand Theft Auto 5 while using RagePluginHook an add-on needed for that to make it work.
Basically, It works like this Main.cs go trough -> Handler.cs that register all the callouts (source code for main and handler down below). It uses LSPDFR.API.MOD and Rage, now i seem to get an Rage.ISpatial is invalid. at Rage.Entity.DistanceTo(ISpatial spatialObject) and I don't really know where in my code I have f up.
I'm getting a Take over Radio Tower Los Santos: Operation is not valid because the specified Rage.ISpatial is invalid. at Rage.Entity.DistanceTo(ISpatial spatialObject)
do anyone know what I did wrong?
Source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Rage;
using LSPD_First_Response.Mod.API;
using LSPD_First_Response.Mod.Callouts;
using System.Drawing;
using Rage.Native;
namespace SpeedyPursuit.Callouts
{
[CalloutInfo("Take over Raido Tower Los Santos", CalloutProbability.Medium)]
public class TakeOverLS : Callout
{
private Ped Suspect;
private Ped Suspect2;
private Ped Suspect3;
private Ped Suspect4;
private Ped Suspect5;
//cops Ped
private Ped Fbisupervisor;
private Ped FbiTeamMember1;
private Ped FbiTeamMember2;
private Ped FbiTeamMember3;
private Ped FbiTeamMember4;
private LHandle Pursuit;
private bool PursuitCreated;
private Vehicle vehicle1;
private Vehicle vehicle2;
private Vehicle vehicle1p;
private Vehicle vehicle2p;
private Vehicle vehicle3p;
private Vehicle vehicle4p;
private Vector3 spawnpV1;
private Vector3 spawnpV2;
private Vector3 spawnV1;
private Vector3 spawnV2;
private Vector3 spawnV1p;
private Vector3 spawnV2p;
private Vector3 spawnV3p;
private Vector3 spawnV4p;
//Cops Spawn
private Vector3 FbisupervisorSpawn;
private Vector3 FbiTeamMember1s;
private Vector3 FbiTeamMember2s;
private Vector3 FbiTeamMember3s;
private Vector3 FbiTeamMember4s;
//locationfollow
private Vector3 followlocation;
private float followheading;
//Cops Blip
private Blip FbisupervisorBlip;
private Blip FbiTeamMember1Blip;
private Blip SuspectBlip;
private Blip SuspectBlip2;
private Blip SuspectBlip3;
private Blip SuspectBlip4;
private Blip SuspectBlip5;
private float heading;
private float headingv1;
private float headingv2;
private float headingv1p;
private float headingv2p;
private float headingv3p;
private float headingv4p;
//cops heading
private float headingfbisup;
private float FbiTeamMember1heading;
private float FbiTeamMember2heading;
private float FbiTeamMember3heading;
private float FbiTeamMember4heading;
private Vector3 Spawnpoint;
private Vector3 Spawnpoint2;
private Vector3 Spawnpoint3;
private Vector3 Spawnpoint4;
private Vector3 Spawnpoint5;
private int counter;
private int counter2;
public override bool OnBeforeCalloutDisplayed()
{
//cops spawn
FbiTeamMember1s = new Vector3(845f, 1285f, 360f);
FbiTeamMember2s = new Vector3(845f, 1283f, 360f);
FbiTeamMember3s = new Vector3(847f, 1284f, 360f);
FbiTeamMember4s = new Vector3(847f, 1286f, 360f);
followlocation = new Vector3(801f, 1276f, 360);
followheading = 86.647f;
Spawnpoint = new Vector3(778f, 1287, 360f);
Spawnpoint2 = new Vector3(779f, 1289, 360f);
Spawnpoint3 = new Vector3(778f, 1270f, 360f);
Spawnpoint4 = new Vector3(787f, 1266f, 360f);
Spawnpoint5 = new Vector3(782f, 1297f, 361f);
FbisupervisorSpawn = new Vector3(855f, 1281f, 359f);
headingv1 = 357.922f;
headingv2 = 51.345f;
// cops heading
headingfbisup = 23.187f;
FbiTeamMember1heading = 174.126f;
FbiTeamMember2heading = 354.127f;
FbiTeamMember3heading = 93.946f;
FbiTeamMember4heading = 255.905f;
headingv1p = 119.149f;
headingv2p = 66.722f;
headingv3p = 320.630f;
headingv4p = 358.971f;
spawnV1 = new Vector3(808f, 1279f, 360f);
spawnV2 = new Vector3(807f, 1272f, 360f);
spawnV1p = new Vector3(855f, 1278f, 359f);
spawnV2p = new Vector3(847f, 1276f, 359f);
spawnV3p = new Vector3(848f, 1290f, 359f);
spawnV4p = new Vector3(843f, 1283f, 359f);
ShowCalloutAreaBlipBeforeAccepting(Spawnpoint, 30f);
AddMinimumDistanceCheck(240f, Spawnpoint);
AddMaximumDistanceCheck(4000f, Spawnpoint);
CalloutMessage = "~r~Multiple suspects~w~ have taken over the Los Santos Radio Tower";
CalloutPosition = Spawnpoint;
Functions.PlayScannerAudioUsingPosition("CRIME_ASSAULT_WITH_A_DEADLY_WEAPON_01 IN_OR_AT", Spawnpoint);
PursuitCreated = false;
return base.OnBeforeCalloutDisplayed();
}
public override bool OnCalloutAccepted()
{
try
{
Game.DisplayNotification("char_call911", "char_call911", "~b~SpeedyPursuit~b~", "~r~TO ALL UNITS~w~", "~r~Dispacth:~w~ All Units responde immediately, Multiple armed suspect have forcefully taken over the radio tower in Los Santos");
Game.DisplayNotification("~r~CODE:~w~ ~Y~3 Response~w~");
Functions.PlayScannerAudio("UNITS_RESPOND_CODE_03_01");
Suspect = new Ped("MP_M_BOGDANGOON", Spawnpoint, heading);
Suspect.IsPersistent = true;
Suspect.BlockPermanentEvents = true;
Suspect2 = new Ped("MP_M_BOGDANGOON", Spawnpoint2, heading);
Suspect2.IsPersistent = true;
Suspect2.BlockPermanentEvents = true;
Suspect3 = new Ped("MP_M_BOGDANGOON", Spawnpoint3, heading);
Suspect3.IsPersistent = true;
Suspect3.BlockPermanentEvents = true;
Suspect4 = new Ped("MP_M_BOGDANGOON", Spawnpoint4, heading);
Suspect4.IsPersistent = true;
Suspect4.BlockPermanentEvents = true;
Suspect5 = new Ped("MP_M_BOGDANGOON", Spawnpoint5, heading);
Suspect5.IsPersistent = true;
Suspect5.BlockPermanentEvents = true;
//Cops ped identifer
Fbisupervisor = new Ped("S_M_Y_SWAT_01", FbisupervisorSpawn, headingfbisup);
Fbisupervisor.IsPersistent = true;
Fbisupervisor.BlockPermanentEvents = true;
FbiTeamMember1 = new Ped("S_M_Y_SWAT_01", FbiTeamMember1s, FbiTeamMember1heading);
FbiTeamMember1.IsPersistent = true;
FbiTeamMember1.BlockPermanentEvents = true;
FbiTeamMember2 = new Ped("S_M_Y_SWAT_01", FbiTeamMember2s, FbiTeamMember2heading);
FbiTeamMember2.IsPersistent = true;
FbiTeamMember2.BlockPermanentEvents = true;
FbiTeamMember3 = new Ped("S_M_Y_SWAT_01", FbiTeamMember3s, FbiTeamMember3heading);
FbiTeamMember3.IsPersistent = true;
FbiTeamMember3.BlockPermanentEvents = true;
FbiTeamMember4 = new Ped("S_M_Y_SWAT_01", FbiTeamMember4s, FbiTeamMember4heading);
FbiTeamMember4.IsPersistent = true;
FbiTeamMember4.BlockPermanentEvents = true;
//swat blip
FbiTeamMember1Blip = FbiTeamMember1.AttachBlip();
FbiTeamMember1Blip.Color = System.Drawing.Color.Green;
FbiTeamMember1Blip.IsRouteEnabled = false;
FbisupervisorBlip = Fbisupervisor.AttachBlip();
FbisupervisorBlip.Color = System.Drawing.Color.Yellow;
FbisupervisorBlip.IsRouteEnabled = true;
SuspectBlip = Suspect.AttachBlip();
SuspectBlip.Color = System.Drawing.Color.Red;
SuspectBlip.IsRouteEnabled = false;
SuspectBlip2 = Suspect.AttachBlip();
SuspectBlip2.Color = System.Drawing.Color.Red;
SuspectBlip2.IsRouteEnabled = false;
SuspectBlip3 = Suspect.AttachBlip();
SuspectBlip3.Color = System.Drawing.Color.Red;
SuspectBlip3.IsRouteEnabled = false;
SuspectBlip4 = Suspect.AttachBlip();
SuspectBlip4.Color = System.Drawing.Color.Red;
SuspectBlip4.IsRouteEnabled = false;
SuspectBlip5 = Suspect.AttachBlip();
SuspectBlip5.Color = System.Drawing.Color.Red;
SuspectBlip5.IsRouteEnabled = false;
Suspect.CanAttackFriendlies = false;
Suspect2.CanAttackFriendlies = false;
Suspect3.CanAttackFriendlies = false;
Suspect4.CanAttackFriendlies = false;
Suspect5.CanAttackFriendlies = false;
vehicle1 = new Vehicle("BURRITO", spawnV1, headingv1);
vehicle2 = new Vehicle("BURRITO", spawnV2, headingv2);
vehicle1p = new Vehicle("RIOT", spawnV1p, headingv1p);
vehicle2p = new Vehicle("RIOT", spawnV2p, headingv2p);
vehicle3p = new Vehicle("POLICE", spawnV3p, headingv3p);
vehicle4p = new Vehicle("RIOT", spawnV4p, headingv4p);
vehicle1p.IsSirenOn = true;
vehicle1p.IsSirenSilent = true;
vehicle2p.IsSirenOn = true;
vehicle2p.IsSirenSilent = true;
vehicle3p.IsSirenOn = true;
vehicle3p.IsSirenSilent = true;
vehicle4p.IsSirenOn = true;
vehicle4p.IsSirenSilent = true;
Suspect.RelationshipGroup = "ATTACKER";
Suspect2.RelationshipGroup = "ATTACKER";
Suspect3.RelationshipGroup = "ATTACKER";
Suspect4.RelationshipGroup = "ATTACKER";
Suspect5.RelationshipGroup = "ATTACKER";
FbiTeamMember1.RelationshipGroup = "COP";
FbiTeamMember2.RelationshipGroup = "COP";
FbiTeamMember3.RelationshipGroup = "COP";
FbiTeamMember4.RelationshipGroup = "COP";
Game.LocalPlayer.Character.RelationshipGroup = "COP";
Game.SetRelationshipBetweenRelationshipGroups("ATTACKER", "COP", Relationship.Hate);
Game.SetRelationshipBetweenRelationshipGroups("COP", "ATTACKER", Relationship.Hate);
Suspect.StaysInGroups = true;
Suspect2.StaysInGroups = true;
Suspect3.StaysInGroups = true;
Suspect4.StaysInGroups = true;
Suspect5.StaysInGroups = true;
FbiTeamMember1.StaysInGroups = true;
FbiTeamMember2.StaysInGroups = true;
FbiTeamMember3.StaysInGroups = true;
FbiTeamMember4.StaysInGroups = true;
FbiTeamMember1.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(FbiTeamMember1, 1, true);
FbiTeamMember2.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(FbiTeamMember2, 1, true);
FbiTeamMember3.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(FbiTeamMember3, 1, true);
FbiTeamMember4.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(FbiTeamMember4, 1, true);
Suspect.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect, 1, true);
Suspect2.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 310, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect2, 1, true);
Suspect3.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 200, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect3, 1, true);
Suspect4.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 170, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect4, 1, true);
Suspect5.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 130, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect5, 1, true);
}
catch
{
Game.LogTrivial("SpeedyPursuit - Something went wrong during loading section");
End();
}
return base.OnCalloutAccepted();
}
public override void Process()
{
base.Process();
if (Game.LocalPlayer.Character.DistanceTo(Fbisupervisor) <= 5f)
{
Game.DisplayHelp("Speak with the SWAT Operatin Lader, To do so press ~y~Y~w~", false);
if (Game.IsKeyDown(Handler.TalkKey))
{
counter++;
if (counter == 1)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Alright listen closely I will only say this once");
}
if (counter == 2)
{
Game.DisplaySubtitle("~b~Offier:~w~ Yes sir");
}
if (counter == 3)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Multiple suspects have forcefully taken over the Radio Station");
}
if (counter == 4)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ They are armed to the teeth with rifles and ammo that can last for days");
}
if (counter == 5)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Negotiations have ended terriblely and our only last option is to lunch ~o~operation payback~w~");
}
if (counter == 6)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ We will force entry through the front gates with swat team ~o~BRAVO~w~");
}
if (counter == 7)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Our priority is to either eliminate the targets or force them to surrender, Secondly find any hostages and free them");
}
if (counter == 8)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ You will lead team ~o~BRAVO~w~, when ready talk to your team and start the operation!");
FbiTeamMember1Blip.Flash(counter, 1);
}
if (counter == 9)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Do you understand my commands!");
}
if (counter == 10)
{
Game.DisplaySubtitle("~b~Offier:~w~ Yes sir!");
}
if (counter == 11)
{
Game.DisplaySubtitle("~b~No further speech here, when ready for breach talk to your team.~w~");
Game.DisplayHelp("Speak with your ~o~swat team~w~", false);
}
}
}
if (Game.LocalPlayer.Character.DistanceTo(FbiTeamMember1) <= 5f)
{
Game.DisplayHelp("Speak with your SWAT Team, To do so press ~y~Y~w~", false);
if (Game.IsKeyDown(Handler.TalkKey))
{
counter2++;
if (counter2 == 1)
{
Game.DisplaySubtitle("~y~SWAT Member:~w~ We are ready to force entry when you are, sir!");
}
if (counter2 == 2)
{
Game.DisplaySubtitle("~b~Offier:~w~ Great, now let's do this");
}
if (counter2 == 3)
{
Game.DisplaySubtitle("~b~Offier:~w~ The gun men are armed and they won't be happy with our entrance");
}
if (counter2 == 4)
{
Game.DisplaySubtitle("~y~SWAT Member:~w~ Understood sir");
FbiTeamMember1.BlockPermanentEvents = false;
FbiTeamMember2.BlockPermanentEvents = false;
FbiTeamMember3.BlockPermanentEvents = false;
FbiTeamMember4.BlockPermanentEvents = false;
}
}
}
if (!PursuitCreated && Game.LocalPlayer.Character.DistanceTo(Suspect) <= 55f)
{
Pursuit = Functions.CreatePursuit();
Functions.AddPedToPursuit(Pursuit, Suspect);
Functions.AddPedToPursuit(Pursuit, Suspect2);
Functions.AddPedToPursuit(Pursuit, Suspect3);
Functions.AddPedToPursuit(Pursuit, Suspect4);
Functions.AddPedToPursuit(Pursuit, Suspect5);
Functions.SetPursuitIsActiveForPlayer(Pursuit, true);
Suspect.Tasks.FightAgainstClosestHatedTarget(200);
Suspect2.Tasks.FightAgainstClosestHatedTarget(200);
Suspect3.Tasks.FightAgainstClosestHatedTarget(200);
Suspect4.Tasks.FightAgainstClosestHatedTarget(200);
Suspect5.Tasks.FightAgainstClosestHatedTarget(200);
PursuitCreated = true;
}
if (PursuitCreated && !Functions.IsPursuitStillRunning(Pursuit))
{
End();
}
if (Game.LocalPlayer.Character.DistanceTo(Suspect) <= 60f)
{
Suspect.BlockPermanentEvents = false;
Suspect2.BlockPermanentEvents = false;
Suspect3.BlockPermanentEvents = false;
Suspect4.BlockPermanentEvents = false;
Suspect5.BlockPermanentEvents = false;
}
if (Game.LocalPlayer.Character.DistanceTo(vehicle1p) > 310f)
{
vehicle1p.Delete();
}
if (Game.LocalPlayer.Character.DistanceTo(vehicle2p) > 310f)
{
vehicle2p.Delete();
}
if (Game.LocalPlayer.Character.DistanceTo(vehicle3p) > 310f)
{
vehicle3p.Delete();
}
if (Game.LocalPlayer.Character.DistanceTo(vehicle4p) > 310f)
{
vehicle4p.Delete();
}
if (Rage.Game.IsKeyDown(Handler.EndCallout))
{
End();
vehicle1.Delete();
vehicle2.Delete();
Suspect.Delete();
Suspect2.Delete();
Suspect3.Delete();
Suspect4.Delete();
Suspect5.Delete();
SuspectBlip.Delete();
SuspectBlip2.Delete();
SuspectBlip3.Delete();
SuspectBlip4.Delete();
SuspectBlip5.Delete();
vehicle1p.Delete();
vehicle2p.Delete();
vehicle3p.Delete();
vehicle4p.Delete();
}
if (!Suspect.Exists() || Game.LocalPlayer.Character.IsDead || !Suspect2.Exists() || !Suspect3.Exists() || !Suspect4.Exists() || !Suspect5.Exists())
{
End();
}
}
public override void End()
{
base.End();
if (SuspectBlip.Exists())
{
SuspectBlip.Delete();
}
if (SuspectBlip2.Exists())
{
SuspectBlip2.Delete();
}
if (SuspectBlip3.Exists())
{
SuspectBlip3.Delete();
}
if (SuspectBlip4.Exists())
{
SuspectBlip4.Delete();
}
if (SuspectBlip5.Exists())
{
SuspectBlip5.Delete();
}
if (FbiTeamMember1Blip.Exists())
{
FbiTeamMember1Blip.Delete();
}
if (FbiTeamMember1Blip.Exists())
{
FbiTeamMember1Blip.Delete();
}
if (FbisupervisorBlip.Exists())
{
FbisupervisorBlip.Delete();
}
if (FbiTeamMember1.Exists())
{
FbiTeamMember1.Dismiss();
}
if (FbiTeamMember2.Exists())
{
FbiTeamMember2.Dismiss();
}
if (FbiTeamMember3.Exists())
{
FbiTeamMember3.Dismiss();
}
if (FbiTeamMember4.Exists())
{
FbiTeamMember4.Dismiss();
}
Game.LogTrivial("SpeedyPursuit - TakeOverLS cleaned up!");
Game.DisplayNotification("~b~SpeedyPursuit~w~ - ~g~Code 4~w~");
Functions.PlayScannerAudio("ATTENTION_ALL_UNITS WE_ARE_CODE 4");
}
}
}
Main.cs
using LSPD_First_Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rage;
using Rage.Native;
using LSPD_First_Response.Mod.API;
using LSPD_First_Response.Mod.Callouts;
using LSPD_First_Response.Engine.Scripting.Entities;
using SpeedyPursuit;
using SpeedyPursuit.Callouts;
using System.Reflection;
namespace SpeedyPursuit
{
public class Main : Plugin
{
public override void Initialize()
{
Functions.OnOnDutyStateChanged += OnOnDutyStateChangedHandler;
Game.LogTrivial("SpeedyPursuit" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " has been initialised.");
Game.LogTrivial("Go on duty to fully load SpeedyPursuit.");
}
public override void Finally()
{
Game.LogTrivial("SpeedyPursuit has been cleaned up.");
}
private static void OnOnDutyStateChangedHandler(bool OnDuty)
{
if (OnDuty)
{
Handler.Initialize();
Game.DisplayNotification("web_lossantospolicedept", "web_lossantospolicedept", "~b~SpeedyPursuit~b~", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " has loaded ~g~successfully~w~", "~o~SpeedyPursuit~w~ Is now running Update name: ~o~Proud-unit~w~");
}
}
}
}
When I look at some object and press the button, I need to do something. When I do it for the first time, it works, but then I don't need to press the button again, I can just look at object. But player must look at object and press the button, not only look
private Collider thisCollider;
public int ActionNumber { get; private set; }
void Start ()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButton("Fire1") && DoPlayerLookAtObject())
ActionsList();
}
bool DoPlayerLookAtObject()
{
int layerMask = 1 << 9;
layerMask = ~layerMask;
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 2.0f, layerMask);
if (isHit && _hit.collider == thisCollider)
return true; // this return true all the time after first interaction with object
else
return false;
}
public bool ActionsList()
{
if (DoPlayerLookAtObject())
switch (thisCollider.name)
{
case "barthender": ActionNumber = 1; return true;
case "doorToStreet": ActionNumber = 2; return true;
default: Debug.Log("Error: Out of range"); break;
}
return false;
}
How I use it:
public OnMousePressCasino onMousePressCasinoBarthender;
public OnMousePressCasino onMousePressCasinoDoorToStreet;
if (onMousePressCasinoBarthender.ActionNumber == 1 &&
onMousePressCasinoBarthender.ActionsList())
// do something
if (onMousePressCasinoDoorToStreet.ActionNumber == 2 &&
onMousePressCasinoDoorToStreet.ActionsList())
// do something
Edit 1 Ignoring player's collider. Video from the game
Okay so basically you're settings you ActionNumber to ( let's say ) 1 and it stays at this value.
To fix this up you would have to set time based reset of that value or just use Raycast all the time in Update ( or LateUpdate ).
Another way would be to make use of event driven programming principles and just fire the event whenever your conditions are met and forget about setting some values.
Making it simple enough :
private Collider thisCollider;
public event EventHandler<MeEventArgs> OnAction;
void Start()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
EventHandler<MeEventArgs> handler = OnAction;
int actionIndex = DoPlayerLookAtObject();
if ( handler != null && actionIndex >= 0)
{
handler(this, new MeEventArgs(actionIndex));
}
}
}
int DoPlayerLookAtObject()
{
int layerMask = 1 << 9;
layerMask = ~layerMask;
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 2.0f, layerMask);
//if (isHit && _hit.collider == thisCollider)
// return true; // this return true all the time after first interaction with object
//else
// return false;
if (isHit && _hit.collider == thisCollider)
return ActionList();
return -1;
}
public int ActionsList()
{
int result = -1;
switch (thisCollider.name)
{
case "barthender": result = 1; break;
case "doorToStreet": result = 2; break;
default: Debug.Log("Error: Out of range"); break;
}
return result;
}
Now create MeEventArgs :
public class MeEventArgs : EventArgs
{
public readonly int Action;
public MeEventArgs(int actionIndex) : base()
{
Action = actionIndex;
}
}
And to use this in code :
public OnMousePressCasino onMousePressCasinoBarthender;
public OnMousePressCasino onMousePressCasinoDoorToStreet;
void Start()
{
onMousePressCasinoBarthender.OnAction += MeAction;
onMousePressCasinoDoorToStreet.OnAction += MeAction;
}
void MeAction(object sender, MeEventArgs e)
{
if(e.Action == 1)
{
// do something
}
else if (e.Action == 2)
{
// do something else.
}
}
public class green : MonoBehaviour
{
private AudioSource source;
public AudioClip sound;
static int result = 0;
void Start()
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
Debug.Log("a");
}
IEnumerator RoutineCheckInputAfter3Minutes()
{
System.Random ran = new System.Random();
int timeToWait = ran.Next(1, 50) * 1000;
Thread.Sleep(timeToWait);
source = this.gameObject.AddComponent<AudioSource>();
source.clip = sound;
source.loop = true;
source.Play();
System.Random r = new System.Random();
result = r.Next(1, 4);
Debug.Log("d");
yield return new WaitForSeconds(3f * 60f);
gm.life -= 1;
Debug.Log("z");
}
public void Update()
{
if (result == 1 && gm.checka == true)
{
Debug.Log("e");
StopCoroutine("RoutineCheckInputAfter3Minutes");
gm.life += 1;
source.Stop();
gm.checka = false;
Debug.Log("j");
}
if (result == 2 && gm.checkb == true)
{
Debug.Log("f");
StopCoroutine("RoutineCheckInputAfter3Minutes");
gm.life += 1;
source.Stop();
gm.checkb = false;
Debug.Log("z");
}
else if (result == 3 && gm.checkc == true)
{
StopCoroutine("RoutineCheckInputAfter3Minutes");
Debug.Log("g");
gm.life += 1;
source.Stop();
gm.checkc = false;
Debug.Log(gm.life);
}
}
}
There are two problems
I want to make music stop and life variable decrease -1, if the user doesn't push any buttons for 3 minutes. But if the user pushes the right button, life variable will be increased + 1. but I don't know how to get null input from the user for 3 minutes.
If I use while for this program, this shuts down… until life is below 0, I want to repeat music which is played on irregular time.
Edit: Don't use Thread in Unity
How Unity works
Alternative to Thread
Couroutine Example 1
Coroutine Example 2
* To put it simple, Thread.Sleep hangs to Unity and Unity can't operate for the time, and that's why it looks like running slow.
You can use coroutines for this problem.
void Start()
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
IEnumerator RoutineCheckInputAfter3Minutes()
{
yield return new WaitForSeconds(3f*60f);
gm.life -= 1;
}
void RightButtonClicked()
{
gm.life += 1;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
Or, you can just turn your a function into a coroutine, if the other code sections work.
void Start()
{
StartCoroutine(a());
}
public IEnumerator a()
{
while (gm.life >= 0)
{
System.Random ran = new System.Random();
int timeToWait = ran.Next(1, 50) * 1000;
yield return new WaitForSeconds(timeToWait);
source = this.gameObject.AddComponent<AudioSource>();
source.clip = sound;
source.loop = true;
source.Play();
System.Random r = new System.Random();
result = r.Next(1, 4);
Debug.Log("d");
}
}
This is an example usage of coroutine based on your code More than this is out of scope:
A pastebin link to code
I dont know how to make ball bounce when hits Paddle´s Top or Bottom, my problem is that the ball goes through the Paddle and then keep going...
So this is the code, some things are in my language so here is translator:
Mustek = Paddle
Mic = Ball
body = Points
HraciPole = Name for graphics array, something like "GameArray"
casovac = name for timer
Kolize = Collision
PohybDolu = MoveUp (bool)
PohybNahoru = MoveDown (bool)
public partial class Form_Pong : Form
{
public static Mustek p1 = new Mustek();
public static Mustek p2 = new Mustek();
public static Mic ball = new Mic();
public int body1 = 0;
public int body2 = 0;
Graphics draw;
public Form_Pong()
{
InitializeComponent();
draw = picBoxHraciPole.CreateGraphics();
}
public static void Draw(Graphics draw)
{
draw.Clear(Color.Black);
draw.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(p1.location, p1.size));
draw.FillRectangle(new SolidBrush(Color.Red), new Rectangle(p2.location, p2.size));
draw.FillRectangle(new SolidBrush(Color.White), new Rectangle(ball.location, ball.size));
}
private void casovac_Tick(object sender, EventArgs e)
{
if (casovac.Interval == 10)
{
p1.location.X = 30;
p1.location.Y = (picBoxHraciPole.Height - p1.size.Height) / 2;
p2.location.X = (picBoxHraciPole.Width - p2.size.Width) - 30;
p2.location.Y = p1.location.Y;
ball.location = new Point(picBoxHraciPole.Width / 2, picBoxHraciPole.Height / 2);
casovac.Interval = 5;
}
Kolize();
Pohyb();
Draw(draw);
}
public void Kolize()
{
if (p1.location.Y < 0)
{
p1.location.Y = 0;
}
if (p1.location.Y + p1.size.Height > picBoxHraciPole.Height)
{
p1.location.Y = picBoxHraciPole.Height - p1.size.Height;
}
if (p2.location.Y < 0)
{
p2.location.Y = 0;
}
if (p2.location.Y + p2.size.Height > picBoxHraciPole.Height)
{
p2.location.Y = picBoxHraciPole.Height - p2.size.Height;
}
if (ball.location.Y < 0)
{
ball.speed.Y = -ball.speed.Y;
}
if (ball.location.Y + ball.size.Height > picBoxHraciPole.Height)
{
ball.speed.Y = -ball.speed.Y;
}
if (ball.location.X < 0)
{
body2 += 1;
labelBody2.Text = body2.ToString();
Reset();
}
if (ball.location.X + ball.size.Width > picBoxHraciPole.Width)
{
body1 +=1;
labelBody1.Text = body1.ToString();
Reset();
}
if (new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p1.location, p1.size)) ||
new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p2.location, p2.size)))
{
ball.speed.X = -ball.speed.X;
}
if (new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p1.location, p1.size)) ||
new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p2.location, p2.size)))
{
}
}
public void Reset()
{
ball.location = new Point(picBoxHraciPole.Width / 2, picBoxHraciPole.Height / 2);
ball.speed.X = -ball.speed.X;
ball.speed.Y = -ball.speed.Y;
}
public static void Pohyb()
{
if (p1.PohybNahoru == true)
{
p1.location.Y -= 8;
}
if (p1.PohybDolu == true)
{
p1.location.Y += 6;
}
if (p2.PohybNahoru == true)
{
p2.location.Y -= 6;
}
if (p2.PohybDolu == true)
{
p2.location.Y += 6;
}
ball.location.X += ball.speed.X;
ball.location.Y += ball.speed.Y;
}
private void Form_Pong_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
p1.PohybNahoru = true;
}
if (e.KeyCode == Keys.S)
{
p1.PohybDolu = true;
}
if (e.KeyCode == Keys.Escape)
{
Application.Exit();
}
if (e.KeyCode == Keys.Up)
{
p2.PohybNahoru = true;
}
if (e.KeyCode == Keys.Down)
{
p2.PohybDolu = true;
}
if (e.KeyCode == Keys.F1)
{
casovac.Enabled = false;
}
if (e.KeyCode == Keys.F2)
{
casovac.Enabled = true;
}
}
private void EnableDoubleBuffering()
{
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
}
private void Form_Pong_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
p1.PohybNahoru = false;
}
if (e.KeyCode == Keys.S)
{
p1.PohybDolu = false;
}
if (e.KeyCode == Keys.Up)
{
p2.PohybNahoru = false;
}
if (e.KeyCode == Keys.Down)
{
p2.PohybDolu = false;
}
}
}
public class Mustek
{
public Point location;
public Size size;
public bool PohybNahoru, PohybDolu;
public int Score;
public Mustek()
{
Score = 0;
size.Width = 25;
size.Height = 125;
}
}
public class Mic
{
public Point location;
public Size size;
public Point speed;
public Mic()
{
speed.X = -5;
speed.Y = 5;
this.size.Width = 25;
this.size.Height = 25;
}
}
The basic logic that you are looking for is
If edge of ball =edge of paddle then change direction so as if x was decreasing bow x is to ve increasing
Once you have that you can work out angles for different conditions such as if it gits the edge of the paddle ect.
Good Day! I have this code but I have an error, for example (I set two players me, and 1 computer). I take the first turn, and the dice respawn with a value of 4 (just an example), the game piece then move from 1st to 4th tile when I touch the screen, when computer turns, it also move from 1st to 4th tile (because I set the result to 4 just an example). Now its my turn again, the dice never respawn and it doesn't wait to touch the screen if (Input.GetMouseButtonDown(0)) and move again by 4...
public class singlePlay : MonoBehaviour {
//Player
public GameObject[] playerprefab;
//Player Clone
public GameObject[] playerprefabC;
//Game Cards and Dice
public GameObject[] situationCard;
public GameObject dice;
int diceresult;
//Game Cards and Dice clone
public GameObject diceclone;
public int currentPlayer;
public int compPlayer;
public int playerTurn;
public string compPlayerstring;
public string playerTurnstring;
//GUI Boolean
bool play = false;
//Game Boolean
bool pieces = false;
bool giveturn = false;
bool myturn = false;
bool diceSpawn = false;
bool moving = false;
bool routine = false;
bool checking = false;
bool compturn = false;
//icon1
public GameObject[] icon;
//population
int[] population = new int[3];
//Tile
public GameObject[] Tile;
int[] playerTile = new int[3]; //current location
int[] playerTileUp = new int [3]; // updated location after dice roll
bool endTurn = false;
void Update ()
{
if (giveturn == true) {
int h = 0;
Giveturn(h);
giveturn = false;
}
if (play == true) {
if (pieces == true){
SpawnPlayer();
pieces = false;
}
if (myturn == true){
compturn = false;
if(diceSpawn == true) {
dice.transform.position = new Vector3(0,0,-1);
diceclone = Instantiate(dice, dice.transform.position, Quaternion.identity) as GameObject;
diceSpawn = false;
}
if (Input.GetMouseButtonDown(0))
{
Debug.Log("click");
diceresult = 4;
Destroy(diceclone);
moving = true;
Updateposition(diceresult);
}
}
else
{
Debug.Log("comp");
myturn = false;
diceresult = 4;
moving = true;
Updateposition(diceresult);
}
}
}
void Giveturn(int k)
{
Debug.Log("" + k);
currentPlayer = k;
if (k == playerTurn) {
Debug.Log("Yes");
compturn = false;
myturn = true;
diceSpawn = true;
moving = false;
}
else
{
Debug.Log("No");
compturn = true;
myturn = false;
moving = false;
}
}
void Updateposition(int diceresult)
{
if (moving == true) {
playerTileUp[currentPlayer] = playerTile[currentPlayer] + diceresult;
Debug.Log("" + playerTileUp[currentPlayer]+ " " +currentPlayer);
routine = true;
StartCoroutine(MyMethod());
}
moving = false;
}
IEnumerator MyMethod()
{
if (routine == true) {
if (myturn == true) {
compturn = false;
}
else
{
myturn = false;
}
int f = playerTile[currentPlayer] + 1;
Debug.Log(" " + currentPlayer );
while (f <= playerTileUp[currentPlayer]) {
Debug.Log("waiting");
yield return new WaitForSeconds(1);
Debug.Log(" " + Tile[f]);
playerprefabC[currentPlayer].transform.position = Tile[f].transform.position;
Debug.Log(" " + currentPlayer);
f++;
}
checking = true;
TrapCheck();
}
routine = false;
}
void TrapCheck()
{
if (checking == true) {
if (playerTileUp[currentPlayer] == 8) {
Debug.Log("Trap spawning");
Instantiate(situationCard[0], situationCard[0].transform.position, Quaternion.identity);
population[currentPlayer] = population[currentPlayer] -1;
}
playerTile[currentPlayer] = playerTileUp[currentPlayer];
Endturn();
myturn = false;
compturn = false;
checking = false;
}
}
void Endturn()
{
currentPlayer++;
Debug.Log(" " + currentPlayer);
if (currentPlayer > compPlayer) {
currentPlayer = 0;
}
Giveturn(currentPlayer);
}
}
There are few things that I could see wrong there already. First while the coroutine is running, it seems you are not preventing the update from running since play remains true. In TrapCheck, you call EndTurn which call GiveTurn and sets myTurn (true) and compTurn (false) booleans. But those two are reset in TrapCheck, myTurn is set back to false. You need to rethink the logic of your class.
A solution would be to use delegate. This would remove many of your boolean that you set and reset. Here is a basic idea:
Action currentUpdate;
bool playerTurn = true;
void Start(){
SetTurn();
}
void Update(){
if(currentUpdate != null)currentUpdate();
}
void SetTurn(){
// Prepare initial setting for moving
if(playerTurn == true){ currentUpdate = PlayerTurn; }
else{ currentUpdate = CompTurn; }
playerTurn = !playerTurn;
}
void PlayerTurn(){
// Check input
// Get dice value
currentUpdate = Move;
}
void CompTurn(){
// Get dice value
currentUpdate = Move;
}
void Move(){
if(position != target){
}else{
SetTurn();
}
}
This is fairly simplified but once you get the thing about delegate (maybe you already know), this will make it all so much more flexible.