// This is called when the mod is first loaded. public override void OnLoad() { // Initialize messages Messages.CloakProgress = ModNetworking.CreateMessageType(DataType.Block, DataType.Single, DataType.Boolean, DataType.Single, DataType.Vector3, DataType.Boolean); // Script after message has been received ModNetworking.Callbacks[Messages.CloakProgress] += message2 => { // Save and convert data that just received from message Block block = (Block)message2.GetData(0); float sizee = (float)message2.GetData(1); bool Activation = (bool)message2.GetData(2); float timer = (float)message2.GetData(3); Vector3 position = (Vector3)message2.GetData(4); bool flashish = (bool)message2.GetData(5); // I used static method so I can get the desired detector script // Note that block.SimBlock is the simulating instance of desired block. if not using SimBlock then the building instance will be given. StealthCloakFieldScript clk = StealthCloakFieldScriptMP.getSCFS(block.SimBlock); if (clk.GetType() == typeof(StealthCloakFieldScriptMP)) { // Some method for syncing ((StealthCloakFieldScriptMP)clk).CloakSizeModifier(sizee, Activation, timer, position, flashish); } }; Messages.CloakSimuStart = ModNetworking.CreateMessageType(DataType.Block); ModNetworking.Callbacks[Messages.CloakSimuStart] += message4 => { Block block = (Block)message4.GetData(0); // The script on cloak block in client PROCloakScript clk = block.SimBlock.GameObject.GetComponent <PROCloakScript>(); // Use the initialization clk.Initialization(); }; }
public override void SimulateFixedUpdateAlways() { if (!StatMaster.isClient) { SetParams(Vector3.Lerp(displacement, Rigidbody.position, 0.2f), Vector3.Lerp(velocity, Rigidbody.velocity, 0.2f), Vector3.Lerp(rotation, Rigidbody.rotation.eulerAngles, 0.2f)); } if (StatMaster.isMP && StatMaster.isHosting) { Message syncc = Messages.PilotPanelSync.CreateMessage(Block.From(this), displacement, velocity, rotation); ModNetworking.SendTo(Machine.Player, syncc); } direction = transform.forward; horizontal = new Vector3(-direction.z / direction.x, 0f, 1f).normalized; T1 = Time.time; dt = Time.fixedDeltaTime; if (disp) { vel0 = vel1; vel1 = velocity; acce = (vel1.magnitude - vel0.magnitude) / dt; overload = (Vector3.Dot((vel1 - vel0), this.transform.up) / dt + (float)38.5 * Vector3.Dot(Vector3.up, this.transform.up)) / (float)38.5; alt = displacement.y; climbrate = velocity.y; pitch = 90 - Mathf.Acos((2 - (direction - Vector3.up).magnitude * (direction - Vector3.up).magnitude) / 2) / Mathf.PI * 180; yaw = rotation.y; roll = Mathf.Sign(direction.x) * (Mathf.Acos((2 - (horizontal - this.transform.up).magnitude * (horizontal - this.transform.up).magnitude) / 2) / Mathf.PI * 180 - 90); } }
public override void SimulateFixedUpdateAlways() { // Things that are really need to be synced ReactivationTimer += Time.fixedDeltaTime * (flashing && DirectionVisualization.IsActive? 5 : 1); FieldSize = 2 * CloakFieldSize.Value; if (Activated) { size = FieldSize * Mathf.Min(ReactivationTimer, CloakExtendingTime.Value) / CloakExtendingTime.Value; } else { size = FieldSize * (1 - Mathf.Min(ReactivationTimer, CloakExtendingTime.Value) / CloakExtendingTime.Value); } if (flashing && DirectionVisualization.IsActive && ReactivationTimer >= CloakExtendingTime.Value) { flashing = false; ReactivationTimer = 0; } CloakSizeModifier(size, flashing); // Bumped here to reduce network cost if (bumpFixedUpdate) { Message cloakInfoP = Messages.CloakProgress.CreateMessage(Block.From(this), size, Activated, ReactivationTimer, this.transform.position, flashing); ModNetworking.SendInSimulation(cloakInfoP); } bumpFixedUpdate = !bumpFixedUpdate; }
public void AfterEdit(MapperType mapper) { // We cannot use undo system for PIOs, because they are dymanic // trying to save them will result in exception on 'undo' while // getting mapper type inside OnEditField if (mapper is MCustom <string> ) { BlockMapper.OnEditField(BlockBehaviour, mapper); } else { Player localPlayer = Player.GetLocalPlayer(); if (localPlayer == null || localPlayer.IsHost) { return; } var tempdata = new XDataHolder(); BlockBehaviour.OnSave(tempdata); tempdata.Encode(out byte[] dataBytes); var message = ModContext.CpuInfoMessage.CreateMessage( this.BlockBehaviour, dataBytes ); ModNetworking.SendToHost(message); } }
private static void LaserMessages() { // Initialize messages Messages.LaserProgress = ModNetworking.CreateMessageType(DataType.Block, DataType.Boolean, DataType.Boolean, DataType.Single, DataType.Boolean, DataType.Vector3); // Script after message has been received ModNetworking.Callbacks[Messages.LaserProgress] += message2 => { // Save and convert data that just received from message Block block = (Block)message2.GetData(0); bool ActivationY = (bool)message2.GetData(1); bool ActivationK = (bool)message2.GetData(2); float length = (float)message2.GetData(3); bool hit = (bool)message2.GetData(4); Vector3 velo = (Vector3)message2.GetData(5); NewLaserBlock clk = block.SimBlock.GameObject.GetComponent <NewLaserBlock>(); // Use the initialization clk.SetMPState(ActivationY, ActivationK, length, hit, velo); }; Messages.LaserSimuStart = ModNetworking.CreateMessageType(DataType.Block); ModNetworking.Callbacks[Messages.LaserSimuStart] += message4 => { Block block = (Block)message4.GetData(0); // The script on cloak block in client NewLaserBlock clk = block.SimBlock.GameObject.GetComponent <NewLaserBlock>(); // Use the initialization clk.OnSimulateStart(); }; }
private void SendExplosionPositionToAll(Vector3 position) { if (StatMaster.isHosting) { Message explosionPositionMsg = Messages.rocketHighExploPosition.CreateMessage(position, bombExplosiveCharge); ModNetworking.SendToAll(explosionPositionMsg); } }
public override void OnSimulateStart() { // This will be execute on host's BlockScript Initialization(); // Therefore message will be sent from here to let all other clients' cloak block to initialize Message cloakStarted = Messages.CloakSimuStart.CreateMessage(Block.From(this)); ModNetworking.SendInSimulation(cloakStarted); }
protected void SendPortalPlacement(Portal portal, ShootState state, Vector3 impact, Vector3 pos, Vector3 normal) { MuzzlePlarticle(portal); VidyaMod.PlayAudio(audioSource, state == ShootState.Place ? clips[portal.index] : clips[2], 0.9f); if (!StatMaster.isLocalSim) { Message targetMessage = portalShotMessageType.CreateMessage(Block.From(this), portal.index, (int)state, impact, pos, normal); ModNetworking.SendToAll(targetMessage); } }
protected void SendTargetPos() { if (!simulationStarted) { return; } if (!StatMaster.isLocalSim) { Message targetMessage = targetingMessageType.CreateMessage(Block.From(this), targeter.transform.position); ModNetworking.SendToAll(targetMessage); } }
//protected override void OnSimulateFixedStart() //{ // if (自动索敌.IsActive && 自动索敌.DisplayInMapper) // { // FUCounter = 1; // FriendlyBlockGUID = new List<Guid>(); // float range = 自动索敌友方范围.Value * 自动索敌友方范围.Value; // foreach (Transform FriendlyOr in Machine.SimulationMachine) // { // if (range >= this.transform.InverseTransformPoint(FriendlyOr.transform.position).sqrMagnitude) // { // FriendlyBlockGUID.Add(FriendlyOr.GetComponent<BlockBehaviour>().Guid); // } // } // } //} public override void SimulateUpdateClient() { //下个目标 if (Machine.Player != Player.GetLocalPlayer()) { return; } if (Key25.IsPressed && 自动索敌.IsActive) { LockingTimer = currentLocking ? 0 : -1; } //烧坏 if (HasBurnedOut && !StatMaster.GodTools.UnbreakableMode) { currentLocking = null; LockingTimer = -1; currentTarget = null; return; } if (自动索敌.IsActive) { return; } //鼠标瞄准模式 if (模式.Value == 1) { Ray raay = Camera.main.ScreenPointToRay(Input.mousePosition); Message lockmessage = Messages.TrackingComputerLock.CreateMessage(Block.From(this), raay.origin, raay.direction); ModNetworking.SendToHost(lockmessage); if (FireOnMouseClick.IsActive && 模式.Value == 1 && Input.GetMouseButtonDown(0)) { Message shotmess = Messages.ModTrackingComputerShot.CreateMessage(Block.From(this)); ModNetworking.SendToHost(shotmess); } } //按键瞄准模式 if (Key1.IsPressed && !HasBurnedOut && 模式.Value == 0) { Ray raay = Camera.main.ScreenPointToRay(Input.mousePosition); Message lockmessage = Messages.TrackingComputerLock.CreateMessage(Block.From(this), raay.origin, raay.direction); ModNetworking.SendToHost(lockmessage); } //按键瞄准模式-取消 if (Key2.IsPressed && 模式.Value == 0) { currentLocking = null; LockingTimer = -1; currentTarget = null; } }
private static void TrackingComputerMessages() { Messages.TrackingComputerLock = ModNetworking.CreateMessageType(DataType.Block, DataType.Vector3, DataType.Vector3); ModNetworking.Callbacks[Messages.TrackingComputerLock] += message6 => { Block block = (Block)message6.GetData(0); // The script on cloak block in client BasicTrackingComputerBehavior clk = block.SimBlock.GameObject.GetComponent <BasicTrackingComputerBehavior>(); // Use the initialization clk.AcquireTarget(new Ray((Vector3)message6.GetData(1), (Vector3)message6.GetData(2))); }; Messages.TrackingComputerSync = ModNetworking.CreateMessageType(DataType.Block, DataType.Vector3, DataType.Boolean); ModNetworking.Callbacks[Messages.TrackingComputerSync] += message7 => { Block block = (Block)message7.GetData(0); // The script on cloak block in client BasicTrackingComputerBehavior clk = block.SimBlock.GameObject.GetComponent <BasicTrackingComputerBehavior>(); // Use the initialization clk.setSign((bool)message7.GetData(2), (Vector3)message7.GetData(1)); }; Messages.ModTrackingComputerShot = ModNetworking.CreateMessageType(DataType.Block); ModNetworking.Callbacks[Messages.ModTrackingComputerShot] += message11 => { Block block = (Block)message11.GetData(0); // The script on cloak block in client ModifiedTurret clk = block.SimBlock.GameObject.GetComponent <ModifiedTurret>(); clk.shot(); }; Messages.MissileGuidanceModeSwitch = ModNetworking.CreateMessageType(DataType.Block, DataType.Integer); ModNetworking.Callbacks[Messages.MissileGuidanceModeSwitch] += message => { Block block = (Block)message.GetData(0); // The script on cloak block in client TrackingComputer clk = block.SimBlock.GameObject.GetComponent <TrackingComputer>(); // Use the initialization clk.MissileGuidanceModeInt = (int)message.GetData(1); clk.MissileVisReplacement((int)message.GetData(1)); }; Messages.OverLoaded = ModNetworking.CreateMessageType(DataType.Block); ModNetworking.Callbacks[Messages.OverLoaded] += message8 => { Block block = (Block)message8.GetData(0); // The script on cloak block in client BasicTrackingComputerBehavior clk = block.SimBlock.GameObject.GetComponent <BasicTrackingComputerBehavior>(); }; }
private void SendClientTargetNull() { if (StatMaster.isHosting) { Message rocketTargetNullMsg = Messages.rocketTargetNullMsg.CreateMessage(parentBlock); Player player1 = Player.GetAllPlayers().Find(player => player.NetworkId == parentBlock.ParentMachine.PlayerID); if (player1 != null) { ModNetworking.SendTo(player1, rocketTargetNullMsg); } ModNetworking.SendToAll(Messages.rocketLostTargetMsg.CreateMessage(parentBlock)); } RocketsController.Instance.RemoveRocketTarget(parentBlock); }
protected void SendPolymorph(MonoBehaviour m, bool heated) { if (!StatMaster.isLocalSim) { LevelEntity le = m.GetComponent <LevelEntity>(); if (le == null) { return; } Entity e = Entity.From(le); Message targetMessage = polymorphMessageType.CreateMessage(Block.From(poultryizer), e, heated); ModNetworking.SendToAll(targetMessage); } }
// This is called when the mod is first loaded. public override void OnLoad() { LaserMessages(); TrackingComputerMessages(); Messages.PilotPanelSync = ModNetworking.CreateMessageType(DataType.Block, DataType.Vector3, DataType.Vector3, DataType.Vector3); ModNetworking.Callbacks[Messages.PilotPanelSync] += message31 => { Block block = (Block)message31.GetData(0); // The script on cloak block in client PilotPanelScript clk = block.SimBlock.GameObject.GetComponent <PilotPanelScript>(); // Use the initialization clk.SetParams((Vector3)message31.GetData(1), (Vector3)message31.GetData(2), (Vector3)message31.GetData(3)); }; }
public override void SimulateUpdateAlways() { if ((launch_key.IsPressed || launch_key.EmulationPressed()) && !rocketScript.Launched) { rocketScript.LaunchEnabled = true; if (StatMaster.isHosting) { var message = LaunchMessage.CreateMessage(BlockBehaviour, rocketScript.Guid.ToString()); ModNetworking.SendToAll(message); } } if (healthBar.health <= 0 && isExploded == false) { rocketScript.Explody(); } }
public void Explody() { if (!StatMaster.isClient) { var message = ExplodeMessage.CreateMessage(Guid.ToString()); ModNetworking.SendToAll(message); rigidbody.isKinematic = true; exploder.Explodey(transform.position); gameObject.GetComponentInChildren <CapsuleCollider>().isTrigger = true; gameObject.GetComponentsInChildren <MeshRenderer>().ToList().Find(match => match.name == "Vis").enabled = false; enabled = false; } }
private void fire() { if (!LaunchEnable && Time.timeScale != 0) { LaunchEnable = true; StartCoroutine(Launch(BulletParticleEffectEvent)); } void BulletParticleEffectEvent() { fireBaseMethod((bullet) => { var message = FireMessage.CreateMessage(BlockBehaviour, Rigidbody.velocity, bullet.GetComponent <RayBulletScript>().Guid.ToString()); ModNetworking.SendToAll(message); }); } }
public override void SimulateUpdateAlways() { if (!StatMaster.isClient) { laserAtOff = HoldingToEmit.IsActive ? !LaserOnOffKey.IsDown : laserAtOff; if (LaserOnOffKey.IsReleased) { laserAtOff = HoldingToEmit.IsActive ? true : !laserAtOff; } laserFX = EffectActivateKey.IsDown; } UpdateThingy(); if (StatMaster.isMP && !StatMaster.isClient) { Message laserInfoP = Messages.LaserProgress.CreateMessage(Block.From(this), laserAtOff, laserFX, LaserLength, BeamHitAnything, this.Rigidbody.velocity); ModNetworking.SendInSimulation(laserInfoP); } }
public void Fire() { if (StatMaster.isClient) { return; } StartCoroutine(Launch(fireEvent)); void fireEvent() { GameObject gameObject = rocketPool.Work.GetChild(0).gameObject; Vector3 position = Vector3.right * Vector3.Project(Rigidbody.velocity, transform.right).magnitude *transform.localScale.x *Time.fixedDeltaTime * 3f; gameObject.transform.localPosition += position; gameObject.transform.SetParent(/*transform.parent*/ Machine.InternalObject.transform); gameObject.SetActive(true); Rigidbody rigidbody = gameObject.GetComponent <Rigidbody>(); rigidbody.isKinematic = false; rigidbody.velocity = Rigidbody.velocity; rigidbody.AddRelativeForce(Vector3.right * 25f, ForceMode.Impulse); RocketScript rocketScript = gameObject.GetComponent <RocketScript>(); rocketScript.LaunchEnabled = true; if (StatMaster.isHosting) { var message = LaunchMessage.CreateMessage(BlockBehaviour, BulletCurrentNumber, rocketScript.Guid.ToString(), position); ModNetworking.SendToAll(message); } StartCoroutine(delay()); IEnumerator delay() { yield return(new WaitForSeconds(rocketScript.DelayEnableCollisionTime)); rigidbody.detectCollisions = true; gameObject.GetComponentInChildren <CapsuleCollider>().isTrigger = false; yield break; } } }
public JsValue Print(JsValue thiz, JsValue[] x) { if (x.Length == 0) { return(null); } if (Time.time - lastPrint < 1) { if (printCount >= 50) { if (printCount == 50) { ++printCount; Debug.LogWarning($"Warning: cpu is emitting too may log lines, cool down"); } return(null); } } else { printCount = 0; lastPrint = Time.time; } ++printCount; var logLine = PrintObject(x[0], 0); var blockPlayer = BlockBehaviour.ParentMachine == null ? null : Player.From(BlockBehaviour.ParentMachine.PlayerID); if (blockPlayer == null || blockPlayer.IsHost) { LogMessage(logLine); } else { // send log to client's machine var message = ModContext.CpuLogMessage.CreateMessage( BlockBehaviour, logLine ); ModNetworking.SendTo(blockPlayer, message); } return(null); }
public void SendRocketFired() { if (!removedFromGroup) { if (StatMaster.isHosting) { Message rocketFiredMsg = Messages.rocketFiredMsg.CreateMessage(BB); ModNetworking.SendTo(Player.GetAllPlayers().Find(player => player.NetworkId == rocket.ParentMachine.PlayerID), rocketFiredMsg); } if (RocketsController.Instance.playerGroupedRockets.TryGetValue(StatMaster.isMP ? rocket.ParentMachine.PlayerID : 0, out Dictionary <KeyCode, HashSet <TimedRocket> > groupedRockets)) { if (groupedRockets.TryGetValue(GroupFireKey.GetKey(0), out HashSet <TimedRocket> rockets)) { rockets.Remove(rocket); } } removedFromGroup = true; } }
void fire() { if (!LaunchEnable && Time.timeScale != 0) { LaunchEnable = true; StartCoroutine(Launch(BulletParticleEffectEvent)); } void BulletParticleEffectEvent() { var bullet = (GameObject)Instantiate(BulletObject, transform.TransformPoint(SpawnPoint + Direction), transform.rotation); bullet.SetActive(true); var bs = bullet.GetComponent <BulletScript>(); bs.Fire(null, (value) => { bs.gameObject.AddComponent <ExplodeScript>().Explodey(ExplodeScript.explosionType.Small, bullet.transform.position, bulletPowerSlider.Value, 3f); bs.GetComponent <TimedSelfDestruct>().Begin(5f); } ); if (StatMaster.isMP && Modding.Common.Player.GetAllPlayers().Count > 1) { var message = FireMessage.CreateMessage(BlockBehaviour, Rigidbody.velocity, bs.Guid.ToString()); ModNetworking.SendToAll(message); } fireAudioSource.PlayOneShot(fireAudioSource.clip); fireAudioSource.pitch = UnityEngine.Random.Range(0.8f, 1.2f); EffectsObject.SetActive(true); EffectsObject.GetComponent <Reactivator>().Switch = true; } }
public void Awake() { // Loading var engine = new Jint.Engine(); //var logic = new Interpreter(); Registers = new Dictionary <Type, Action <BlockBehaviour, KeyInputController> >(); Unregisters = new Dictionary <Type, Action <BlockBehaviour> >(); ModConsole.RegisterCommand("script", args => { var text = string.Join(" ", args); //var func = logic.PrepareScript(text); //logic.AddExtFunc(func, "print", (ctx, x) => { ModConsole.Log(x[0]?.ToString()); return null; }, true); //logic.SetScript(func); //var res = logic.ContinueScript(1000); Func <JsValue, JsValue[], JsValue> printCb = (thiz, x) => { ModConsole.Log(x[0]?.ToObject().ToString()); return(x[0]); }; JsValue curV = null; Func <JsValue, JsValue[], JsValue> irqv = (thiz, x) => { curV = x[0]; return(null); }; var script = new JavaScriptParser(text, Jint.Engine.DefaultParserOptions).ParseScript(); engine.SetValue("print", printCb); engine.SetValue("irqv", irqv); engine.SetScript(script); engine.Executor.OnLog = (x) => ModConsole.Log(x?.ToString()); bool cli = false; engine.Executor.OnNextStatement = () => { if (cli) { return; } cli = true; try { if (curV != null) { engine.Invoke(curV); } } finally { cli = false; } }; var res = engine.ContinueScript(1000); ModConsole.Log(res?.ToString()); }, "exec script"); ModConsole.RegisterCommand("cpuapi", args => { foreach (var line in SingleInstance <Blocks.Api.CpuApi> .Instance.GetHelp()) { ModConsole.Log(line); } }, "print cpu api list"); ModConsole.RegisterCommand("sensordbg", args => { DrawSensorDebug = args.Length < 1 ? false : args[0] == "true"; }, "print sensor debug points"); CpuBlock.Create(this); // These creator functions find corresponding block in game prefabs // and replace it with inheritor ExtLogicGate.Create(this); ExtAltimeterBlock.Create(this); ExtSpeedometerBlock.Create(this); ExtAnglometerBlock.Create(this); ExtSensorBlock.Create(this); ModConsole.Log($"Logic mod Awake"); Events.OnMachineSimulationToggle += Events_OnMachineSimulationToggle; LineMaterial = new Material(Shader.Find("Hidden/Internal-Colored")); LineMaterial.hideFlags = HideFlags.HideAndDontSave; LineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); LineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); LineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off); LineMaterial.SetInt("_ZWrite", 0); Camera.onPostRender += DrawConnectingLines; Events.OnBlockInit += InitBlock; CpuInfoMessage = ModNetworking.CreateMessageType(new DataType[] { DataType.Block, DataType.ByteArray }); CpuLogMessage = ModNetworking.CreateMessageType(new DataType[] { DataType.Block, DataType.String }); ModNetworking.Callbacks[CpuInfoMessage] += (Action <Message>)((msg) => { Player localPlayer = Player.GetLocalPlayer(); if (msg == null || localPlayer == null || !localPlayer.IsHost) { return; } var block = msg.GetData(0) as Modding.Blocks.Block; if (!(block?.BlockScript is CpuBlock cpu)) { return; } if (block.Machine == localPlayer.Machine) { return; // don't read updates for MY machine! } cpu.AfterEdit_ServerRecv((byte[])msg.GetData(1)); }); ModNetworking.Callbacks[CpuLogMessage] += (Action <Message>)((msg) => { if (msg == null) { return; } var block = msg.GetData(0) as Modding.Blocks.Block; if (!(block?.BlockScript is CpuBlock cpu)) { return; } cpu.LogMessage((string)msg.GetData(1)); }); }
private void Update() { if (!isCollision) { if (Time.timeScale == 0f) { return; } _deltaTime = Time.smoothDeltaTime / Time.timeScale; Vector3 gravityVelocity = (!StatMaster.GodTools.GravityDisabled) ? (bulletPropertise.GravityAcceleration) : Vector3.zero; Vector3 dragVelocity = -(bulletPropertise.Velocity.normalized * bulletPropertise.Drag); bulletPropertise.Velocity += gravityVelocity + dragVelocity; ePoint = sPoint + bulletPropertise.Velocity * _deltaTime; lineRenderer.SetPosition(0, sPoint); if (Physics.Raycast(sPoint, bulletPropertise.Velocity, out hitInfo, (sPoint - ePoint).magnitude) && bulletPropertise.ColliderEnabled == true) { if ((hitInfo.transform == gunbodyTransform && gunbodyTransform != null)) { shootingNothing(); } else { if (hasRigidbody(hitInfo, out rigidbody_Aim)) { shootingSomething(); } else if (hitInfo.collider.isTrigger == false) { shootingSomething(); } else { shootingNothing(); } } } else { shootingNothing(); } } else { lineRenderer.enabled = false; Destroy(gameObject); } bool hasRigidbody(RaycastHit hit, out Rigidbody rigidbody) { var value = false; rigidbody = null; if (hit.rigidbody != null && hit.rigidbody.isKinematic == false) { value = true; rigidbody = hit.rigidbody; return(value); } else if (hit.collider.attachedRigidbody != null && hit.collider.attachedRigidbody.isKinematic == false) { value = true; rigidbody = hit.collider.attachedRigidbody; return(value); } else { var blockBehaviour = hit.transform.GetComponentInParent <BlockBehaviour>() ?? hit.transform.GetComponentInChildren <BlockBehaviour>(); if (blockBehaviour != null) { rigidbody = blockBehaviour.transform.GetComponent <Rigidbody>(); if (rigidbody != null && rigidbody.isKinematic == false) { value = true; return(value); } } var levelEntity = hit.transform.GetComponentInParent <LevelEntity>() ?? hit.transform.GetComponentInChildren <LevelEntity>(); if (levelEntity != null) { rigidbody = levelEntity.transform.GetComponent <Rigidbody>(); if (rigidbody != null && rigidbody.isKinematic == false) { value = true; return(value); } } return(value); } } void shootingSomething() { var targetType = "stone"; lineRenderer.SetPosition(1, hitInfo.point); isCollision = true; if (!StatMaster.isClient) { OnCollisionEvent?.Invoke(rigidbody_Aim); targetType = createImpactEffect(); var message = ImpactMessage.CreateMessage(Guid.ToString(), targetType, hitInfo.point, hitInfo.normal); ModNetworking.SendToAll(message); } } void shootingNothing() { lineRenderer.SetPosition(1, ePoint); sPoint = ePoint; } }
public override void OnSimulateStart() { string ShaderString = UseNotTrans.IsActive ? "Legacy Shaders/Reflective/Bumped Specular" : "Particles/Additive"; rHInfos = new List <RHInfo>(); Especially = new GameObject("TheThings"); if (!UseLegacy.IsActive) { CINU = new CheckIfNeeeeeeedsUpdate(CheckIfNeedsUpdate); CTRGO = new GameObject("CubeTube"); if (CTR == null) { CTR = CTRGO.AddComponent <CustomTubeRenderer>(); //CTR.material = new Material(Shader.Find("Particles/Alpha Blended")); //CTR.crossSegments = 1; CTR.flatAtDistance = 1; CTR.maxRebuildTime = 0.01f; } CTRGO.transform.SetParent(transform); CTRGO.transform.localPosition = Vector3.forward * 1.1f; CTRGO.transform.rotation = transform.rotation; } else { CINU = new CheckIfNeeeeeeedsUpdate(LegacyCheckIfNeedsUpdate); if (lr == null) { lr = this.gameObject.AddComponent <LineRenderer>(); } lr.material = new Material(Shader.Find(ShaderString)); lr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; lr.SetWidth(0.08f, 0.08f); Color ArgColour = LaserColourSlider.Value; lr.SetColors(Color.Lerp(ArgColour, Color.black, 0.45f), Color.Lerp(ArgColour, Color.clear, 0.2f)); lr.SetVertexCount(0); } Especially.transform.SetParent(this.transform); Especially.transform.localPosition = Vector3.forward * 1.1f; Especially.transform.LookAt(this.transform.position); //lr.material.SetColors(Color.Lerp(ArgColour, Color.black, 0.45f), // Color.Lerp(ArgColour, Color.clear, 0.2f)); laserAtOff = !LaserOnOffToggle.IsActive; PointLight = Especially.AddComponent <Light>(); PointLight.color = LaserColourSlider.Value; PointLight.intensity = 3 * Math.Max(0.25f, PenetrativeLengthMultiplier.Value); PointLight.range = Mathf.Max(this.transform.localScale.x, this.transform.localScale.y) * LaserWidth.Value * 3f; PointLight.shadows = LightShadows.Soft; TheToggleProvideLight = LightOptionToggle.IsActive ? 1 : 0; if (ShrinkEffectToggle.IsActive && !PSR) { PS = Especially.AddComponent <ParticleSystem>(); ParticleSystem.Particle NewParticle = new ParticleSystem.Particle(); PS.startSize = 0.2f; PS.startColor = new Color(LaserColourSlider.Value.r, LaserColourSlider.Value.g, LaserColourSlider.Value.b, 0.5f); PS.startLifetime = ChargeHoldGasp.Value * 0.45f; PS.startSpeed = -0.5f; PS.scalingMode = ParticleSystemScalingMode.Shape; PS.SetParticles(new ParticleSystem.Particle[] { NewParticle }, 1); ParticleSystem.ColorOverLifetimeModule PSCOLM = PS.colorOverLifetime; PSCOLM.color = new Gradient() { alphaKeys = new GradientAlphaKey[] { new GradientAlphaKey(0, 0), new GradientAlphaKey(0.8f, 0.2f), new GradientAlphaKey(1, 1) }, colorKeys = new GradientColorKey[] { new GradientColorKey(PS.startColor, 0), new GradientColorKey(PS.startColor, 1) } }; PSCOLM.enabled = true; PS.simulationSpace = ParticleSystemSimulationSpace.World; //ParticleSystem.Burst BUTS = new ParticleSystem.Burst(10, 10, 1000); PSR = Especially.GetComponent <ParticleSystemRenderer>(); //PSR.material = new Material(Shader.Find("Particles/Alpha Blended")); PSR.material = new Material(Shader.Find(ShaderString)); PSR.material.mainTexture = (ModResource.GetTexture("LaserParticle.png")); } if (StatMaster.isMP && !StatMaster.isClient) { Message laserSimu = Messages.LaserSimuStart.CreateMessage(Block.From(this)); ModNetworking.SendInSimulation(laserSimu); } }
public MessageController() { //Initiating messages Messages.rocketFiredMsg = ModNetworking.CreateMessageType(DataType.Block); Messages.rocketTargetBlockBehaviourMsg = ModNetworking.CreateMessageType(DataType.Block, DataType.Block); Messages.rocketTargetEntityMsg = ModNetworking.CreateMessageType(DataType.Entity, DataType.Block); Messages.rocketTargetNullMsg = ModNetworking.CreateMessageType(DataType.Block); Messages.rocketRayToHostMsg = ModNetworking.CreateMessageType(DataType.Vector3, DataType.Vector3, DataType.Block); Messages.rocketHighExploPosition = ModNetworking.CreateMessageType(DataType.Vector3, DataType.Single); Messages.rocketLockOnMeMsg = ModNetworking.CreateMessageType(DataType.Block, DataType.Integer); Messages.rocketLostTargetMsg = ModNetworking.CreateMessageType(DataType.Block); //Initiating callbacks ModNetworking.Callbacks[Messages.rocketHighExploPosition] += (Message msg) => { if (StatMaster.isClient) { Vector3 position = (Vector3)msg.GetData(0); float bombExplosiveCharge = (float)msg.GetData(1); int levelBombCategory = 4; int levelBombID = 5001; float radius = 7f; float power = 3600f; float torquePower = 100000f; float upPower = 0.25f; try { GameObject bomb = UnityEngine.Object.Instantiate(PrefabMaster.LevelPrefabs[levelBombCategory].GetValue(levelBombID).gameObject); bomb.transform.position = position; ExplodeOnCollide bombControl = bomb.GetComponent <ExplodeOnCollide>(); bomb.transform.localScale = Vector3.one * bombExplosiveCharge; bombControl.radius = radius * bombExplosiveCharge; bombControl.power = power * bombExplosiveCharge; bombControl.torquePower = torquePower * bombExplosiveCharge; bombControl.upPower = upPower; bombControl.Explodey(); } catch { } } }; ModNetworking.Callbacks[Messages.rocketFiredMsg] += (Message msg) => { Block rocketBlock = (Block)msg.GetData(0); TimedRocket rocket = rocketBlock.GameObject.GetComponent <TimedRocket>(); RocketsController.Instance.UpdateRocketFiredStatus(rocket); }; ModNetworking.Callbacks[Messages.rocketTargetBlockBehaviourMsg] += (Message msg) => { #if DEBUG Debug.Log("Receive block target"); #endif Block rocketBlock = (Block)msg.GetData(1); RocketScript rocket = rocketBlock.GameObject.GetComponent <RocketScript>(); rocket.target = ((Block)msg.GetData(0)).GameObject.transform; rocket.targetCollider = rocket.target.gameObject.GetComponentInChildren <Collider>(true); }; ModNetworking.Callbacks[Messages.rocketTargetEntityMsg] += (Message msg) => { #if DEBUG Debug.Log("Receive entity target"); #endif Block rocketBlock = (Block)msg.GetData(1); RocketScript rocket = rocketBlock.GameObject.GetComponent <RocketScript>(); rocket.target = ((Entity)msg.GetData(0)).GameObject.transform; rocket.targetCollider = rocket.target.gameObject.GetComponentInChildren <Collider>(true); }; ModNetworking.Callbacks[Messages.rocketTargetNullMsg] += (Message msg) => { #if DEBUG Debug.Log("Receive entity target"); #endif Block rocketBlock = (Block)msg.GetData(0); RocketScript rocket = rocketBlock.GameObject.GetComponent <RocketScript>(); rocket.target = null; rocket.targetCollider = null; }; ModNetworking.Callbacks[Messages.rocketRayToHostMsg] += (Message msg) => { Block rocketBlock = (Block)msg.GetData(2); RocketScript rocket = rocketBlock.GameObject.GetComponent <RocketScript>(); rocket.rayFromClient = new Ray((Vector3)msg.GetData(0), (Vector3)msg.GetData(1)); rocket.activeGuide = false; rocket.receivedRayFromClient = true; }; ModNetworking.Callbacks[Messages.rocketLockOnMeMsg] += (Message msg) => { Block rocket = (Block)msg.GetData(0); int targetMachineID = (int)msg.GetData(1); RocketsController.Instance.UpdateRocketTarget(rocket.InternalObject, targetMachineID); }; ModNetworking.Callbacks[Messages.rocketLostTargetMsg] += (Message msg) => { Block rocket = (Block)msg.GetData(0); RocketsController.Instance.RemoveRocketTarget(rocket.InternalObject); }; }
public static void CreateMessageTypes() { tankTypeMessage = ModNetworking.CreateMessageType(DataType.ByteArray, DataType.Boolean); ModNetworking.Callbacks[tankTypeMessage] += LJTMachine.OnTankTypeMessageReceive; }
private void SendRayToHost(Ray ray) { Message rayToHostMsg = Messages.rocketRayToHostMsg.CreateMessage(ray.origin, ray.direction, /*BB*/ parentBlock); ModNetworking.SendToHost(rayToHostMsg); }
protected static void SetupNetworking() { targetingMessageType = ModNetworking.CreateMessageType(DataType.Block, DataType.Vector3); ModNetworking.Callbacks[targetingMessageType] += ProcessRemoteTargeting; }
private IEnumerator explodey(explosionType explosiontype, Vector3 position, float power, float radius) { if (StatMaster.isClient) { yield break; } if (isExplodey) { yield break; } else { fireEffect = getExplodeEffectObject(explosiontype); if (ExplosionType == explosionType.Big) { fireEffect.transform.FindChild("Debris").localRotation = Quaternion.AngleAxis(UnityEngine.Random.Range(0f, 360f), Vector3.up); } fireEffect.transform.position = position; if (!StatMaster.isClient) { var message = ExplodyMessage.CreateMessage((int)explosiontype, position); ModNetworking.SendToAll(message); } } yield return(new WaitForFixedUpdate()); isExplodey = true; fireEffect.SetActive(true); OnExplode?.Invoke(); //定义爆炸位置为炸弹位置 Vector3 explosionPos = position; //这个方法用来返回球型半径之内(包括半径)的所有碰撞体collider[] Collider[] colliders = Physics.OverlapSphere(explosionPos, radius); //遍历返回的碰撞体,如果是刚体,则给刚体添加力 foreach (Collider hit in colliders) { if (hit.attachedRigidbody != null) { float force = UnityEngine.Random.Range(30000f, 50000f) * power * (Vector3.Distance(hit.transform.position, explosionPos) / (radius + 0.25f)); hit.attachedRigidbody.AddExplosionForce(force, explosionPos, radius); hit.attachedRigidbody.AddTorque(force * Vector3.Cross((hit.transform.position - explosionPos), Vector3.up)); reduceBlockHealth(hit.attachedRigidbody.gameObject); } } OnExploded?.Invoke(colliders); yield return(new WaitForSeconds(3f)); fireEffect.SetActive(false); OnExplodeFinal?.Invoke(); //------------------------------------------------------------- void reduceBlockHealth(GameObject gameObject) { var bhb = gameObject.GetComponent <BlockHealthBar>(); if (bhb != null) { bhb.DamageBlock(1); } } //--------------------------------------------------------------- }