Esempio n. 1
0
        protected void SpawnObjectEx()
        {
            Transform parent;

            if (SpawnParent == null)
            {
                parent = CoreUtils.GetWorldRoot();
            }
            else
            {
                parent = SpawnParent;
            }

            Vector3 position = OverrideTransform ? OverridePosition : transform.position;
            Vector3 rotation = OverrideTransform ? OverrideRotation : transform.eulerAngles;

            var go = WorldUtils.SpawnEntity(FormId, null, position, rotation, parent);

            go.SetActive(ActivateObject);

            if (!string.IsNullOrEmpty(EffectId))
            {
                WorldUtils.SpawnEffect(EffectId, position, rotation, parent);
            }

            OnSpawnEvent.Invoke(go, this);
        }
Esempio n. 2
0
        /// <summary>
        /// Spawn an entity into the world (entities/*)
        /// </summary>
        public static GameObject SpawnEntity(string formID, string thingID, Vector3 position, Quaternion rotation, Transform parent)
        {
            if (parent == null)
            {
                parent = CoreUtils.GetWorldRoot();
            }

            var prefab = CoreUtils.LoadResource <GameObject>("Entities/" + formID);

            if (prefab == null)
            {
                if (ConfigState.Instance.UseVerboseLogging)
                {
                    Debug.LogError($"Failed to spawn entity \"{formID}\" because prefab does not exist!");
                }
                return(null);
            }

            var go = UnityEngine.Object.Instantiate(prefab, position, rotation, parent) as GameObject;

            if (string.IsNullOrEmpty(thingID))
            {
                thingID = string.Format("{0}_{1}", go.name.Replace("(Clone)", "").Trim(), GameState.Instance.NextUID);
            }
            go.name = thingID;
            return(go);
        }
Esempio n. 3
0
        private void DestroyBullet()
        {
            if (DestroyEffect != null)
            {
                Instantiate(DestroyEffect, transform.position, transform.rotation, CoreUtils.GetWorldRoot());
            }

            if (DamageRadius > 0)
            {
                //no damage falloff, just a simple radius
                var overlapped = Physics2D.OverlapCircleAll(transform.position, DamageRadius, LayerMask.GetMask("Default", "Actor"));
                foreach (var obj in overlapped)
                {
                    bool otherIsPlayer = (obj.tag == "Player") || (obj.GetComponent <PlayerController>() != null);

                    var itd = obj.GetComponent <ITakeDamage>();
                    if (itd != null && ((otherIsPlayer && CollideWithPlayer) || (!otherIsPlayer && CollideWithMonster)))
                    {
                        itd.TakeDamage(Damage);
                    }
                }
            }

            Destroy(gameObject);
        }
Esempio n. 4
0
        /// <summary>
        /// Spawns a hit puff, setting position and variant
        /// </summary>
        public static GameObject SpawnHitPuff(string effect, Vector3 position, int hitMaterial)
        {
            GameObject puff = null;

            try
            {
                if (!string.IsNullOrEmpty(effect))
                {
                    puff = WorldUtils.SpawnEffect(effect, position, Vector3.zero, CoreUtils.GetWorldRoot());

                    if (puff != null)
                    {
                        var puffScript = puff.GetComponent <HitPuffScript>();

                        if (puffScript != null)
                        {
                            puffScript.ActivateVariant(hitMaterial);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Failed to spawn HitPuff!");
                Debug.LogException(e);
            }

            return(puff);
        }
Esempio n. 5
0
        static void ListEntitiesInScene()
        {
            StringBuilder sb       = new StringBuilder();
            var           entities = CoreUtils.GetWorldRoot().GetComponentsInChildren <BaseController>(true);

            foreach (var entity in entities)
            {
                sb.AppendLine($"{entity.gameObject.name} ({entity.FormID ?? entity.EditorFormID} : {entity.GetType().Name}) [{entity.transform.position.ToString("F2")}] {(entity.isActiveAndEnabled ? "" : "(disabled)")} {(entity is ITakeDamage && WorldUtils.IsAlive(entity) ? "" : "(dead)")}");
            }

            ConsoleModule.WriteLine(sb.ToString());
        }
Esempio n. 6
0
        public static void InitiateDialogue(string dialogue, bool pause, DialogueFinishedDelegate callback)
        {
            DialogueController.CurrentDialogue = dialogue;
            DialogueController.CurrentCallback = callback;
            var prefab = CoreUtils.LoadResource <GameObject>("UI/DialogueSystem");
            var go     = GameObject.Instantiate <GameObject>(prefab, CoreUtils.GetWorldRoot());

            if (pause)
            {
                LockPauseModule.PauseGame(PauseLockType.All, go);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Finds all entities with form ID (entity name)
        /// </summary>
        public static IList <BaseController> FindEntitiesWithFormID(string formID)
        {
            List <BaseController> foundObjects = new List <BaseController>();

            foreach (BaseController c in CoreUtils.GetWorldRoot().gameObject.GetComponentsInChildren <BaseController>(true))
            {
                if (c.FormID == formID)
                {
                    foundObjects.Add(c);
                }
            }

            return(foundObjects);
        }
Esempio n. 8
0
        /// <summary>
        /// Finds all entities with CommonCore tag
        /// </summary>
        public static IList <BaseController> FindEntitiesWithTag(string tag)
        {
            List <BaseController> foundObjects = new List <BaseController>();

            foreach (BaseController c in CoreUtils.GetWorldRoot().gameObject.GetComponentsInChildren <BaseController>(true))
            {
                if (c.Tags != null && c.Tags.Count > 0 && c.Tags.Contains(tag))
                {
                    foundObjects.Add(c);
                }
            }

            return(foundObjects);
        }
Esempio n. 9
0
        protected void ActivateEntityPlaceholders()
        {
            var entityPlaceholders = CoreUtils.GetWorldRoot().GetComponentsInChildren <EntityPlaceholder>(false);

            foreach (var ep in entityPlaceholders)
            {
                try
                {
                    ep.SpawnEntity();
                }
                catch (Exception e)
                {
                    Debug.LogError("Failed to activate an entity placeholder!");
                    Debug.LogException(e);
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Gets the player object (or null if it doesn't exist)
        /// </summary>
        public static GameObject GetPlayerObject()
        {
            if (PlayerObject != null)
            {
                return(PlayerObject);
            }

            GameObject go = GameObject.FindGameObjectWithTag("Player");

            if (go != null)
            {
                PlayerObject = go;
                return(go);
            }

            go = GameObject.Find("Player");

            if (go != null)
            {
                PlayerObject = go;
                return(go);
            }

            var tf = CoreUtils.GetWorldRoot().FindDeepChild("Player");

            if (tf != null)
            {
                go = tf.gameObject;
            }

            if (go != null)
            {
                PlayerObject = go;
                return(go);
            }

            if (ConfigState.Instance.UseVerboseLogging)
            {
                Debug.LogWarning("Couldn't find player!");
            }

            return(null);
        }
Esempio n. 11
0
        /// <summary>
        /// Spawn an effect into the world (Effects/*)
        /// </summary>
        public static GameObject SpawnEffect(string effectID, Vector3 position, Quaternion rotation, Transform parent, bool useUniqueId)
        {
            if (parent == null)
            {
                parent = CoreUtils.GetWorldRoot();
            }

            var prefab = CoreUtils.LoadResource <GameObject>("Effects/" + effectID);

            if (prefab == null)
            {
                return(null);
            }

            var go = UnityEngine.Object.Instantiate(prefab, position, rotation, parent) as GameObject;

            go.name = string.Format("{0}_{1}", go.name.Replace("(Clone)", "").Trim(), useUniqueId ? GameState.Instance.NextUID.ToString() : "fx");

            return(go);
        }
Esempio n. 12
0
        private void HandleShooting()
        {
            DidJustFire = false;

            if (LockPauseModule.IsInputLocked() || !PlayerController.PlayerInControl || PlayerController.PlayerIsDead || !PlayerController.PlayerCanShoot)
            {
                return;
            }

            if (PlayerController.GetButtonDown(DefaultControls.Fire) && TimeUntilNextShot <= 0)
            {
                var gunPivot = PlayerController.IsCrouched ? GunPivotCrouched : GunPivot;

                //aiming!
                Vector2 fireVector    = (Vector2)transform.right * Mathf.Sign(PlayerController.transform.localScale.x);
                float   spawnDistance = ((Vector2)transform.position - (Vector2)GunPivot.position).magnitude;
                float   aimY          = PlayerController.GetAxis("Vertical");
                if (aimY > AimDeadzone || (!PlayerController.IsTouchingGround && aimY < -AimDownDeadzone))
                {
                    float aimX = PlayerController.GetAxis("Horizontal");
                    fireVector = new Vector2(aimX, aimY).normalized;
                }
                Vector2 spawnPosition = (Vector2)gunPivot.position + fireVector * spawnDistance; //this technique misaligns the bullet if the muzzle isn't aligned with the pivot. Can you fix it?
                LastFireVector = fireVector;

                Quaternion bulletRotation = Quaternion.FromToRotation(Vector3.right, fireVector);

                var go = Instantiate(BulletPrefab, spawnPosition, bulletRotation, CoreUtils.GetWorldRoot());
                var rb = go.GetComponent <Rigidbody2D>();
                rb.velocity = (fireVector * BulletVelocity);// + (Vector2.right * PlayerController.Rbody.velocity.x);
                var bs = go.GetComponent <BulletScript>();
                bs.Damage          = BulletDamage;
                TimeUntilNextShot += FireInterval;
                DidJustFire        = true;

                //play effect, anim
                AttackSound.Ref()?.Play();
                GunAnimator.Play("Fire"); //we rely on the Animator to return to idle state
            }
        }
        private void Die()
        {
            IsDead = true;

            if (Animator != null)
            {
                if (Animator.enabled)
                {
                    Animator.Play("Die");
                }
                else
                {
                    Animator.enabled = true;
                }
            }

            DieSound.Ref()?.Play();

            if (DeathEffect != null)
            {
                Instantiate(DeathEffect, transform.position, Quaternion.identity, CoreUtils.GetWorldRoot());
            }

            if (DeathEvent != null)
            {
                DeathEvent.Invoke();
            }

            if (DeactivateOnDeath)
            {
                gameObject.SetActive(false);
            }

            if (GrantScore > 0)
            {
                GameState.Instance.Player1Score += GrantScore;
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Spawn an entity into the world (entities/*)
        /// </summary>
        public static GameObject SpawnEntity(string formID, string thingID, Vector3 position, Quaternion rotation, Transform parent)
        {
            if (parent == null)
            {
                parent = CoreUtils.GetWorldRoot();
            }

            var prefab = CoreUtils.LoadResource <GameObject>("Entities/" + formID);

            if (prefab == null)
            {
                return(null);
            }

            var go = UnityEngine.Object.Instantiate(prefab, position, rotation, parent) as GameObject;

            if (string.IsNullOrEmpty(thingID))
            {
                thingID = string.Format("{0}_{1}", go.name.Replace("(Clone)", "").Trim(), GameState.Instance.NextUID);
            }
            go.name = thingID;
            return(go);
        }
Esempio n. 15
0
        /// <summary>
        /// Finds the player spawn point by name
        /// </summary>
        /// <remarks>
        /// <para>Selects from active PlayerSpawnPoints, then active without PlayerSpawnPoint, then inactive without PlayerSpawnPoint</para>
        /// </remarks>
        public static GameObject FindPlayerSpawn(string spawnPointName)
        {
            Transform[]      transforms           = CoreUtils.GetWorldRoot().GetComponentsInChildren <Transform>(true);
            var              potentialSpawnPoints = transforms.Select(t => t.gameObject).Where(g => g.name == spawnPointName);
            PlayerSpawnPoint spawnPoint           = potentialSpawnPoints.Where(g => g.activeInHierarchy).Select(g => g.GetComponent <PlayerSpawnPoint>()).Where(p => p != null).FirstOrDefault();

            if (spawnPoint != null)
            {
                return(spawnPoint.gameObject);
            }
            GameObject spawnPointObject = potentialSpawnPoints.Where(g => g.activeInHierarchy).FirstOrDefault();

            if (spawnPointObject != null)
            {
                return(spawnPointObject);
            }
            spawnPointObject = potentialSpawnPoints.Where(g => g.GetComponent <PlayerSpawnPoint>() == null).FirstOrDefault();
            if (spawnPointObject != null)
            {
                return(spawnPointObject);
            }

            return(null);
        }
Esempio n. 16
0
        /// <summary>
        /// Spawn an effect into the world (Effects/*)
        /// </summary>
        public static GameObject SpawnEffect(string effectID, Vector3 position, Quaternion rotation, Transform parent, bool useUniqueId)
        {
            if (parent == null)
            {
                parent = CoreUtils.GetWorldRoot();
            }

            var prefab = CoreUtils.LoadResource <GameObject>("Effects/" + effectID);

            if (prefab == null)
            {
                if (ConfigState.Instance.UseVerboseLogging)
                {
                    Debug.LogError($"Failed to spawn effect \"{effectID}\" because prefab does not exist!");
                }
                return(null);
            }

            var go = UnityEngine.Object.Instantiate(prefab, position, rotation, parent) as GameObject;

            go.name = string.Format("{0}_{1}", go.name.Replace("(Clone)", "").Trim(), useUniqueId ? GameState.Instance.NextUID.ToString() : "fx");

            return(go);
        }
Esempio n. 17
0
        public void Kill()
        {
            IsDead                = true;
            Rigidbody.velocity    = Vector2.zero;
            Rigidbody.isKinematic = true;
            Collider.enabled      = false;
            AttackState           = EnemyAttackState.Approaching;
            AttackTimeInState     = 0;
            DamagedEffectObject.Ref()?.SetActive(false);
            IdleSound.Ref()?.Stop();
            DieSound.Ref()?.Play();

            if (DeathEffectPrefab != null)
            {
                Instantiate(DeathEffectPrefab, transform.position, transform.rotation, CoreUtils.GetWorldRoot());
            }

            StartCoroutine(CoHideModel());

            if (GrantScore > 0)
            {
                //TODO 1P/2P handling, we would need to pass the bullet or HitInfo in ITakeDamage like RpgGame and add a property to BulletScript for which player fired or something
                GameState.Instance.Player1Score += GrantScore;
            }
        }
Esempio n. 18
0
        public void TakeDamage(float damage)
        {
            if (DamageEffectPrefab != null)
            {
                Instantiate(DamageEffectPrefab, transform.position, Quaternion.identity, CoreUtils.GetWorldRoot());
            }

            if (Health / MaxHealth <= DamageDisplayRatio && DamagedEffectObject != null && !DamagedEffectObject.activeSelf)
            {
                DamagedEffectObject.SetActive(true);
            }

            if (MaxHealth > 0)
            {
                Health -= damage;
                if (Health <= 0 && !IsDead)
                {
                    StartDeathSequence();
                }
            }
        }
Esempio n. 19
0
        private void DoAttack()
        {
            if (BulletPrefab != null)
            {
                //shoot point
                Transform shootPoint = ShootPoint.Ref() ?? transform;

                //velocity vector
                Vector2 velocityVector = Vector2.down * BulletVelocity;

                //do bullet attack
                var go = Instantiate(BulletPrefab, shootPoint.position, Quaternion.identity, CoreUtils.GetWorldRoot());
                var rb = go.GetComponent <Rigidbody2D>();
                rb.velocity = velocityVector;
                var bs = go.GetComponent <BulletScript>();
                bs.Damage = AttackDamage;
            }
        }
Esempio n. 20
0
        public override void ActivateVariant(int hitMaterial)
        {
            if (Variants == null || Variants.Count == 0)
            {
                WorldUtils.SpawnEffect(FallbackEffect, transform.position, transform.eulerAngles, CoreUtils.GetWorldRoot());
                return;
            }

            string foundEffect = null;

            foreach (var variant in Variants)
            {
                if (variant.HitMaterial == hitMaterial)
                {
                    foundEffect = variant.Effect;
                    break;
                }
            }

            if (!string.IsNullOrEmpty(foundEffect))
            {
                WorldUtils.SpawnEffect(foundEffect, transform.position, transform.eulerAngles, CoreUtils.GetWorldRoot());
            }
            else
            {
                WorldUtils.SpawnEffect(FallbackEffect, transform.position, transform.eulerAngles, CoreUtils.GetWorldRoot());
            }

            if (DestroyAfterSpawn)
            {
                Destroy(this.gameObject);
            }
        }
Esempio n. 21
0
        private void PresentNewFrame(Frame f)
        {
            TryCallScript(f?.Scripts?.BeforePresent, f);

            //special handling for blank frames
            if (f is BlankFrame)
            {
                CurrentFrameObject = f;
                ScriptingModule.CallNamedHooked("DialogueOnPresent", this, CurrentFrameObject);
                TryCallScript(f?.Scripts?.OnPresent, f);
                OnChoiceButtonClick(0);
                return;
            }

            //create trace node
            var traceNode = new DialogueTraceNode();

            traceNode.Path = $"{CurrentSceneName}.{CurrentFrameName}";

            //present music
            if (!string.IsNullOrEmpty(f.Music))
            {
                if (!(AudioPlayer.Instance.IsMusicSetToPlay(MusicSlot.Cinematic) && AudioPlayer.Instance.GetMusicName(MusicSlot.Cinematic) == f.Music))
                {
                    AudioPlayer.Instance.SetMusic(f.Music, MusicSlot.Cinematic, 1.0f, true, false);
                    AudioPlayer.Instance.StartMusic(MusicSlot.Cinematic);
                }
            }
            else if (f.Music != null) //null = no change, empty = no music
            {
                AudioPlayer.Instance.ClearMusic(MusicSlot.Cinematic);
            }

            //present audio
            string voiceClipName         = $"{CurrentSceneName}/{CurrentFrameName}";
            string voiceClipNameOverride = f.Options.VoiceOverride;

            if (!string.IsNullOrEmpty(voiceClipNameOverride))
            {
                if (voiceClipNameOverride.StartsWith("/"))
                {
                    voiceClipName = voiceClipNameOverride.TrimStart('/');
                }
                else
                {
                    voiceClipName = $"{CurrentSceneName}/{voiceClipNameOverride}";
                }
            }
            if (VoiceAudioSource.isPlaying)
            {
                VoiceAudioSource.Stop();
            }
            var voiceClip = CCBase.GetModule <AudioModule>().GetSound(voiceClipName, SoundType.Voice, !GameParams.DialogueVerboseLogging); //GetModule<T> is now preferred

            if (voiceClip != null)
            {
                VoiceAudioSource.clip   = voiceClip;
                VoiceAudioSource.volume = f.Options.VoiceVolume ?? 1f;
                VoiceAudioSource.Play();
            }

            //present background
            BackgroundImage.sprite = null;
            BackgroundImage.gameObject.SetActive(false);
            if (!string.IsNullOrEmpty(f.Background))
            {
                var sprite = CoreUtils.LoadResource <Sprite>("Dialogue/bg/" + f.Background);
                if (sprite != null)
                {
                    BackgroundImage.sprite = sprite;
                    BackgroundImage.gameObject.SetActive(true);
                }
                else
                {
                    if (GameParams.DialogueVerboseLogging)
                    {
                        CDebug.LogEx($"Couldn't find face sprite Dialogue/bg/{f.Background}", LogLevel.Verbose, this);
                    }
                }
            }

            //size panel
            float faceYOffset      = 0;
            var   framePanelHeight = f.Options.PanelHeight;
            var   panelHeight      = framePanelHeight == ChoicePanelHeight.Default ? GameParams.DialoguePanelHeight : framePanelHeight;

            switch (panelHeight)
            {
            case ChoicePanelHeight.Half:
                if (!Mathf.Approximately(ChoicePanel.rect.height, DefaultPanelHeight / 2f))
                {
                    ChoicePanel.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, DefaultPanelHeight / 2f);
                }
                faceYOffset = -(DefaultPanelHeight / 2f);
                break;

            case ChoicePanelHeight.Variable:
                CDebug.LogEx($"{nameof(ChoicePanelHeight)} {ChoicePanelHeight.Variable} is not supported!", LogLevel.Warning, this);
                break;

            case ChoicePanelHeight.Fixed:
                ChoicePanel.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, f.Options.PanelHeightPixels);
                faceYOffset = -(DefaultPanelHeight - f.Options.PanelHeightPixels);
                break;

            default:
                if (!Mathf.Approximately(ChoicePanel.rect.height, DefaultPanelHeight))
                {
                    ChoicePanel.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, DefaultPanelHeight);     //correct?
                }
                break;
            }

            //show/hide name text
            if (f.Options.HideNameText)
            {
                NameTextPanel.gameObject.SetActive(false);
            }
            else
            {
                NameTextPanel.gameObject.SetActive(true);
            }

            //present image
            FaceImage.sprite = null;
            FaceImage.gameObject.SetActive(false);
            if (!string.IsNullOrEmpty(f.Image))
            {
                //attempt to present image
                var sprite = CoreUtils.LoadResource <Sprite>("Dialogue/char/" + f.Image);
                if (sprite != null)
                {
                    //Debug.Log(sprite.name);

                    Vector2 canvasSize = ((RectTransform)FaceImage.canvas.transform).rect.size;

                    float spriteX = sprite.texture.width * (100f / sprite.pixelsPerUnit);
                    float spriteY = sprite.texture.height * (100f / sprite.pixelsPerUnit);

                    switch (f.ImagePosition)
                    {
                    case FrameImagePosition.Fill:     //works
                        FaceImage.rectTransform.localPosition = Vector3.zero;
                        FaceImage.rectTransform.sizeDelta     = canvasSize;
                        break;

                    case FrameImagePosition.Contain:     //works
                    {
                        FaceImage.rectTransform.localPosition = Vector3.zero;

                        float imageRatio = (float)sprite.texture.width / (float)sprite.texture.height;         //force float division!
                        float rectRatio  = canvasSize.x / canvasSize.y;

                        if (imageRatio > rectRatio)         //image is wider than rect
                        {
                            FaceImage.rectTransform.sizeDelta = new Vector2(canvasSize.x, canvasSize.x / imageRatio);
                        }
                        else         //image is narrower than rect
                        {
                            FaceImage.rectTransform.sizeDelta = new Vector2(canvasSize.y * imageRatio, canvasSize.y);
                        }
                    }
                    break;

                    case FrameImagePosition.Cover:     //works
                    {
                        FaceImage.rectTransform.localPosition = Vector3.zero;

                        float imageRatio = (float)sprite.texture.width / (float)sprite.texture.height;
                        float rectRatio  = canvasSize.x / canvasSize.y;

                        if (imageRatio > rectRatio)         //image is wider than rect
                        {
                            FaceImage.rectTransform.sizeDelta = new Vector2(canvasSize.y * imageRatio, canvasSize.y);
                        }
                        else         //image is narrower than rect
                        {
                            FaceImage.rectTransform.sizeDelta = new Vector2(canvasSize.x, canvasSize.x / imageRatio);
                        }
                    }
                    break;

                    case FrameImagePosition.Character:     //works
                        FaceImage.rectTransform.localPosition = new Vector3(0, faceYOffset + (GameParams.DialogueDrawPortraitHigh ? 140 : 100), 0);
                        FaceImage.rectTransform.sizeDelta     = new Vector2(spriteX, spriteY);
                        break;

                    case FrameImagePosition.CharacterBottom:                  //works
                    {
                        float yPos = (-(canvasSize.y / 2f)) + (spriteY / 2f); //I think we want SpriteY and not pixels directly

                        FaceImage.rectTransform.localPosition = new Vector3(0, yPos, 0);
                        FaceImage.rectTransform.sizeDelta     = new Vector2(spriteX, spriteY);
                    }
                    break;

                    case FrameImagePosition.Battler:     //deliberately broken
                        CDebug.LogEx($"FrameImagePosition {f.ImagePosition} is not supported!", LogLevel.Warning, this);
                        FaceImage.rectTransform.localPosition = Vector3.zero;
                        FaceImage.rectTransform.sizeDelta     = new Vector2(spriteX, spriteY);
                        break;

                    default:     //works
                        FaceImage.rectTransform.localPosition = Vector3.zero;
                        FaceImage.rectTransform.sizeDelta     = new Vector2(spriteX, spriteY);;
                        break;
                    }

                    FaceImage.sprite = sprite;
                    FaceImage.gameObject.SetActive(true);
                }
                else
                {
                    if (GameParams.DialogueVerboseLogging)
                    {
                        CDebug.LogEx($"Couldn't find face sprite Dialogue/char/{f.Image}", LogLevel.Verbose, this);
                    }
                }
            }

            //present camera
            try
            {
                if (!string.IsNullOrEmpty(f.CameraDirection) && !f.CameraDirection.StartsWith("Default", StringComparison.OrdinalIgnoreCase))
                {
                    if (CameraController == null)
                    {
                        var cameraGo = Instantiate(CameraPrefab, CoreUtils.GetWorldRoot());
                        CameraController = cameraGo.GetComponent <DialogueCameraController>();
                    }

                    CameraController.Activate(f.CameraDirection);
                }
                else
                {
                    CameraController.Ref()?.Deactivate();
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to point camera ({f.CameraDirection})");
                Debug.LogException(e);
            }

            //present hidden objects
            var objectsToHide = f.Options.HideObjects;

            if (objectsToHide != null)
            {
                var hiddenObjectsToShow = HiddenObjects.Except(objectsToHide);
                UnhideObjects(hiddenObjectsToShow);

                var newObjectsToHide = objectsToHide.Except(HiddenObjects);
                HideObjects(newObjectsToHide);

                HiddenObjects.Clear();
                HiddenObjects.UnionWith(objectsToHide);
            }
            else
            {
                UnhideAllObjects();
            }

            //present text
            string nameText = Sub.Macro(f.NameText);

            TextTitle.text = nameText;
            string mainText = Sub.Macro(f.Text);

            TextMain.text = mainText;

            //save text to trace (note use of null instead of null-or-empty)
            traceNode.Speaker = (f.Options.TraceSpeaker == null) ? (string.IsNullOrEmpty(nameText) ? GetDefaultTraceSpeaker(f) : nameText) : Sub.Macro(f.Options.TraceSpeaker);
            traceNode.Text    = (f.Options.TraceText == null) ? mainText : Sub.Macro(f.Options.TraceText);

            //clear buttons
            Navigator.ClearButtons();
            foreach (Transform t in ScrollChoiceContent)
            {
                Destroy(t.gameObject);
            }
            ScrollChoiceContent.DetachChildren();
            ButtonAlternateContinue.gameObject.SetActive(false);

            //present buttons and frame
            if (f is ChoiceFrame choiceFrame)
            {
                ChoicePanel.gameObject.SetActive(true);

                ScrollChoice.gameObject.SetActive(true);
                ButtonContinue.gameObject.SetActive(false);

                //ChoiceFrame cf = (ChoiceFrame)f;
                var buttons = new List <Button>();
                for (int i = 0; i < choiceFrame.Choices.Length; i++)
                {
                    ChoiceNode cn = choiceFrame.Choices[i];

                    string prependText = string.Empty;
                    bool   showChoice  = true;
                    bool   lockChoice  = false;

                    if (cn.ShowCondition != null)
                    {
                        showChoice = cn.ShowCondition.Evaluate();
                    }
                    if (cn.HideCondition != null && showChoice)
                    {
                        showChoice = !cn.HideCondition.Evaluate();
                    }

                    //skill checks
                    if (cn.SkillCheck != null)
                    {
                        bool isPossible = cn.SkillCheck.CheckIfPossible();

                        if (!GameParams.ShowImpossibleSkillChecks && !isPossible)
                        {
                            showChoice = false;
                        }

                        if (!GameParams.AttemptImpossibleSkillChecks && !isPossible)
                        {
                            lockChoice = true;
                        }

                        string passValue = cn.SkillCheck.CheckType == SkillCheckType.Soft ? $"{(int)(cn.SkillCheck.GetApproximatePassChance() * 100)}%" : cn.SkillCheck.Value.ToString();

                        prependText = $"[{Sub.Replace(cn.SkillCheck.Target, "RPG_AV")} {passValue}] ";
                    }

                    if (showChoice)
                    {
                        GameObject choiceGO = Instantiate <GameObject>(ButtonPrefab, ScrollChoiceContent);
                        Button     b        = choiceGO.GetComponent <Button>();
                        b.interactable = !lockChoice;
                        b.gameObject.SetActive(true);
                        b.transform.Find("Text").GetComponent <Text>().text = prependText + Sub.Macro(cn.Text);
                        int idx = i;
                        b.onClick.AddListener(delegate { OnChoiceButtonClick(idx); });
                        buttons.Add(b);
                    }
                }

                Navigator.AttachButtons(buttons);
            }
            else if (f is ImageFrame imageFrame)
            {
                string nextText = string.IsNullOrEmpty(f.NextText) ? Sub.Replace("DefaultNextText", "IGUI_DIALOGUE", false) : f.NextText;

                if (imageFrame.AllowSkip)
                {
                    ChoicePanel.gameObject.SetActive(false);
                    ScrollChoice.gameObject.SetActive(false);

                    Button b = ButtonAlternateContinue;
                    b.gameObject.SetActive(true);
                    b.transform.Find("Text").GetComponent <Text>().text = nextText;
                    Navigator.AttachButtons(new Button[] { b });
                }
                else
                {
                    ChoicePanel.gameObject.SetActive(false);
                    ButtonAlternateContinue.gameObject.SetActive(false);
                }

                if (imageFrame.HideSkip)
                {
                    CDebug.LogEx("Image frame HideSkip is deprecated and not implemented (use AllowSkip=false instead)", LogLevel.Warning, this);
                }

                if (imageFrame.UseTimer)
                {
                    StartWaitAndAdvance(imageFrame.TimeToShow);
                }
            }
            else if (f is TextFrame textFrame)
            {
                ChoicePanel.gameObject.SetActive(true);
                ScrollChoice.gameObject.SetActive(false);

                string nextText = string.IsNullOrEmpty(f.NextText) ? Sub.Replace("DefaultNextText", "IGUI_DIALOGUE", false) : f.NextText;

                Button b = ButtonContinue;
                b.gameObject.SetActive(textFrame.AllowSkip);
                b.transform.Find("Text").GetComponent <Text>().text = nextText;
                Navigator.AttachButtons(new Button[] { b });

                if (textFrame.UseTimer)
                {
                    StartWaitAndAdvance(textFrame.TimeToShow);
                }
            }
            else
            {
                throw new NotImplementedException($"Frame type {f.GetType().Name} is not supported");
            }

            //apply theme
            ApplyThemeToPanel();

            CurrentFrameObject = f;

            ScriptingModule.CallNamedHooked("DialogueOnPresent", this, CurrentFrameObject);
            TryCallScript(f?.Scripts?.OnPresent, f);

            if (f.Options.TraceIgnore)
            {
                traceNode.Ignored = true;
            }
            Trace.Nodes.Add(traceNode);
        }
Esempio n. 22
0
 public static void PushModal(LevelUpModalCallback callback)
 {
     if (GameParams.UseCustomLeveling)
     {
         var go    = Instantiate <GameObject>(CoreUtils.LoadResource <GameObject>(AltPrefab), CoreUtils.GetWorldRoot());
         var modal = go.GetComponent <GameUI.LevelUpModal>();
         modal.Callback = callback;
         if (IngameMenuController.Current != null)
         {
             go.transform.SetParent(IngameMenuController.Current.EphemeralRoot.transform, false);
         }
     }
     else
     {
         var go    = Instantiate <GameObject>(CoreUtils.LoadResource <GameObject>(DefaultPrefab), CoreUtils.GetWorldRoot());
         var modal = go.GetComponent <DefaultLevelUpModal>();
         modal.Callback = callback;
         if (IngameMenuController.Current != null)
         {
             go.transform.SetParent(IngameMenuController.Current.EphemeralRoot.transform, false);
         }
     }
 }
Esempio n. 23
0
        private void PresentNewFrame(Frame f)
        {
            //special handling for blank frames
            if (f is BlankFrame)
            {
                CurrentFrameObject = f;
                OnChoiceButtonClick(0);
                return;
            }

            //present music
            if (!string.IsNullOrEmpty(f.Music))
            {
                if (!(AudioPlayer.Instance.IsMusicSetToPlay(MusicSlot.Cinematic) && AudioPlayer.Instance.GetMusicName(MusicSlot.Cinematic) == f.Music))
                {
                    AudioPlayer.Instance.SetMusic(f.Music, MusicSlot.Cinematic, 1.0f, true, false);
                    AudioPlayer.Instance.StartMusic(MusicSlot.Cinematic);
                }
            }
            else
            {
                AudioPlayer.Instance.ClearMusic(MusicSlot.Cinematic);
            }

            //present audio
            if (VoiceAudioSource.isPlaying)
            {
                VoiceAudioSource.Stop();
            }
            var voiceClip = CCBase.GetModule <AudioModule>().GetSound($"{CurrentSceneName}/{CurrentFrameName}", SoundType.Voice); //GetModule<T> is now preferred

            if (voiceClip != null)
            {
                VoiceAudioSource.clip = voiceClip;
                VoiceAudioSource.Play();
            }

            //present background
            BackgroundImage.sprite = null;
            BackgroundImage.gameObject.SetActive(false);
            if (!string.IsNullOrEmpty(f.Background))
            {
                var sprite = CoreUtils.LoadResource <Sprite>("Dialogue/bg/" + f.Background);
                if (sprite != null)
                {
                    BackgroundImage.sprite = sprite;
                    BackgroundImage.gameObject.SetActive(true);
                }
                else
                {
                    CDebug.LogEx($"Couldn't find face sprite Dialogue/bg/{f.Background}", LogLevel.Verbose, this);
                }
            }

            //present image
            FaceImage.sprite = null;
            FaceImage.gameObject.SetActive(false);
            if (!string.IsNullOrEmpty(f.Image))
            {
                //attempt to present image
                var sprite = CoreUtils.LoadResource <Sprite>("Dialogue/char/" + f.Image);
                if (sprite != null)
                {
                    //Debug.Log(sprite.name);

                    float spriteX = sprite.texture.width * (100f / sprite.pixelsPerUnit);
                    float spriteY = sprite.texture.height * (100f / sprite.pixelsPerUnit);

                    switch (f.ImagePosition)
                    {
                    case FrameImagePosition.Fill:
                        FaceImage.rectTransform.localPosition = Vector3.zero;
                        FaceImage.rectTransform.sizeDelta     = FaceImage.canvas.pixelRect.size;
                        break;

                    case FrameImagePosition.Character:
                        FaceImage.rectTransform.localPosition = new Vector3(0, 100, 0);
                        FaceImage.rectTransform.sizeDelta     = new Vector2(spriteX, spriteY);
                        break;

                    default:
                        //center, no scale
                        FaceImage.rectTransform.localPosition = Vector3.zero;
                        FaceImage.rectTransform.sizeDelta     = new Vector2(spriteX, spriteY);
                        break;
                    }

                    FaceImage.sprite = sprite;
                    FaceImage.gameObject.SetActive(true);
                }
                else
                {
                    CDebug.LogEx($"Couldn't find face sprite Dialogue/char/{f.Image}", LogLevel.Verbose, this);
                }
            }

            //present camera
            try
            {
                if (!string.IsNullOrEmpty(f.CameraDirection) && !f.CameraDirection.StartsWith("Default", StringComparison.OrdinalIgnoreCase))
                {
                    if (CameraController == null)
                    {
                        var cameraGo = Instantiate(CameraPrefab, CoreUtils.GetWorldRoot());
                        CameraController = cameraGo.GetComponent <DialogueCameraController>();
                    }

                    CameraController.Activate(f.CameraDirection);
                }
                else
                {
                    CameraController.Ref()?.Deactivate();
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to point camera ({f.CameraDirection})");
                Debug.LogException(e);
            }

            //present text
            TextTitle.text = Sub.Macro(f.NameText);
            TextMain.text  = Sub.Macro(f.Text);

            //clear buttons
            foreach (Transform t in ScrollChoiceContent)
            {
                Destroy(t.gameObject);
            }
            ScrollChoiceContent.DetachChildren();

            //present buttons
            if (f is ChoiceFrame)
            {
                ScrollChoice.gameObject.SetActive(true);
                ButtonContinue.gameObject.SetActive(false);

                ChoiceFrame cf = (ChoiceFrame)f;
                for (int i = 0; i < cf.Choices.Length; i++)
                {
                    ChoiceNode cn = cf.Choices[i];

                    string prependText = string.Empty;
                    bool   showChoice  = true;
                    bool   lockChoice  = false;

                    if (cn.ShowCondition != null)
                    {
                        showChoice = cn.ShowCondition.Evaluate();
                    }
                    if (cn.HideCondition != null && showChoice)
                    {
                        showChoice = !cn.HideCondition.Evaluate();
                    }

                    //skill checks
                    if (cn.SkillCheck != null)
                    {
                        bool isPossible = cn.SkillCheck.CheckIfPossible();

                        if (!GameParams.ShowImpossibleSkillChecks && !isPossible)
                        {
                            showChoice = false;
                        }

                        if (!GameParams.AttemptImpossibleSkillChecks && !isPossible)
                        {
                            lockChoice = true;
                        }

                        string passValue = cn.SkillCheck.CheckType == SkillCheckType.Soft ? $"{(int)(cn.SkillCheck.GetApproximatePassChance() * 100)}%" : cn.SkillCheck.Value.ToString();

                        prependText = $"[{Sub.Replace(cn.SkillCheck.Target, "IGUI_AV")} {passValue}] ";
                    }

                    if (showChoice)
                    {
                        GameObject choiceGO = Instantiate <GameObject>(ButtonPrefab, ScrollChoiceContent);
                        Button     b        = choiceGO.GetComponent <Button>();
                        b.interactable = !lockChoice;
                        b.gameObject.SetActive(true);
                        b.transform.Find("Text").GetComponent <Text>().text = prependText + Sub.Macro(cn.Text);
                        int idx = i;
                        b.onClick.AddListener(delegate { OnChoiceButtonClick(idx); });
                    }
                }
            }
            else // if(f is TextFrame)
            {
                ScrollChoice.gameObject.SetActive(false);

                string nextText = string.IsNullOrEmpty(f.NextText) ? Sub.Replace("DefaultNextText", "IGUI_DIALOGUE", false) : f.NextText;

                Button b = ButtonContinue;
                b.gameObject.SetActive(true);
                b.transform.Find("Text").GetComponent <Text>().text = nextText;
            }

            CurrentFrameObject = f;
        }
Esempio n. 24
0
        public static void PushModal(InventoryModel inventory, ContainerModel container, bool isShop, ContainerCallback callback)
        {
            var go    = Instantiate <GameObject>(CoreUtils.LoadResource <GameObject>(DefaultPrefab), CoreUtils.GetWorldRoot());
            var modal = go.GetComponent <ContainerModal>();

            modal.Inventory = inventory;
            modal.Container = container;
            modal.IsShop    = isShop;
            modal.Callback  = callback;
        }
Esempio n. 25
0
        private void HandleGrenadeThrow()
        {
            if (LockPauseModule.IsInputLocked() || !PlayerInControl || PlayerIsDead || !PlayerCanShoot)
            {
                return;
            }

            if (GetButtonDown("Fire2") && Bombs > 0)
            {
                Vector2    fireVector     = (Quaternion.AngleAxis(GrenadeAngle, Vector3.forward) * Vector3.right) * new Vector2(Mathf.Sign(transform.localScale.x), 1);
                Quaternion bulletRotation = Quaternion.FromToRotation(Vector3.right, fireVector);

                var go = Instantiate(GrenadePrefab, GrenadeThrowPoint.position, bulletRotation, CoreUtils.GetWorldRoot());
                var rb = go.GetComponent <Rigidbody2D>();
                rb.velocity = (fireVector * GrenadeVelocity);// + Rigidbody.velocity;

                Bombs--;
            }
        }
Esempio n. 26
0
        private IEnumerator CoSpawnCorpse()
        {
            yield return(new WaitForSeconds(CorpseSpawnDelay));

            var go = Instantiate(CorpsePrefab, transform.position, Quaternion.identity, CoreUtils.GetWorldRoot());

            go.transform.localScale = Vector3.Scale(go.transform.localScale, new Vector3(Mathf.Sign(transform.localScale.x), 1, 1)); //flip handling
        }
Esempio n. 27
0
        private void DoAttack()
        {
            if (BulletPrefab != null)
            {
                //shoot point
                Transform shootPoint = ShootPoint.Ref() ?? transform;

                //velocity vector
                Vector2 velocityVector = Vector2.zero;
                if (!FireBulletAtTarget || Target == null)
                {
                    velocityVector = ((Vector2)transform.right * Mathf.Sign(transform.localScale.x) * BulletVelocity);// + Rigidbody.velocity;
                }
                else
                {
                    velocityVector = ((Vector2)Target.transform.position - (Vector2)shootPoint.position).normalized * BulletVelocity;
                }

                //do bullet attack
                var go = Instantiate(BulletPrefab, shootPoint.position, Quaternion.identity, CoreUtils.GetWorldRoot());
                var rb = go.GetComponent <Rigidbody2D>();
                rb.velocity = velocityVector;
                var bs = go.GetComponent <BulletScript>();
                bs.Damage = AttackDamage;
            }
            else
            {
                //do melee attack

                if (Target != null)
                {
                    float distToTarget = ((Vector2)Target.transform.position - (Vector2)transform.position).magnitude;
                    if (distToTarget < MeleeRange)
                    {
                        var itd = Target.GetComponent <ITakeDamage>();
                        if (itd != null)
                        {
                            itd.TakeDamage(AttackDamage);
                        }
                    }
                }

                //if we don't have a target we can't melee attack, nor can we attack something that isn't our target. I'm sure that will never cause any problems whatsoever
            }
        }
Esempio n. 28
0
        private void EjectShell()
        {
            if (ShellEjectPoint == null || ShellPrefab == null || ShellEjectPoint.childCount == 0)
            {
                //can't eject shell
                return;
            }

            Transform shellDirTransform = ShellEjectPoint.GetChild(0);
            ShellEjectionComponent shellEjectionComponent = ShellEjectPoint.GetComponent <ShellEjectionComponent>();

            //var shell = Instantiate(ShellPrefab, ShellEjectPoint.position, ShellEjectPoint.rotation, CoreUtils.GetWorldRoot());
            var shell = WorldUtils.SpawnEffect(ShellPrefab, ShellEjectPoint.position, ShellEjectPoint.rotation.eulerAngles, CoreUtils.GetWorldRoot());

            if (shell == null)
            {
                return;
            }

            //shell parameters (use ShellEjectionComponent if available)
            float shellScale;
            float shellVelocity;
            float shellTorque;
            float shellRandomVelocity;
            float shellRandomTorque;

            if (shellEjectionComponent)
            {
                shellScale          = shellEjectionComponent.ShellScale;
                shellVelocity       = shellEjectionComponent.ShellVelocity;
                shellTorque         = shellEjectionComponent.ShellTorque;
                shellRandomVelocity = shellEjectionComponent.ShellRandomVelocity;
                shellRandomTorque   = shellEjectionComponent.ShellRandomTorque;
            }
            else
            {
                //legacy stupid hacky shit

                shellScale    = shellDirTransform.localScale.x;
                shellVelocity = shellDirTransform.localScale.z;
                shellTorque   = shellDirTransform.localScale.y;

                shellRandomVelocity = 0;
                shellRandomTorque   = 0;
            }

            //scale the shell, make it move
            shell.transform.localScale = Vector3.one * shellScale;
            var shellRB = shell.GetComponent <Rigidbody>();

            if (shellRB != null)
            {
                Vector3 velocityDirection = shellDirTransform.forward;

                Vector3 playerVelocity = WeaponComponent.PlayerController.MovementComponent.Velocity;
                Vector3 randomVelocity = new Vector3(UnityEngine.Random.Range(-1f, 1f) * shellRandomVelocity, UnityEngine.Random.Range(-1f, 1f) * shellRandomVelocity, UnityEngine.Random.Range(-1f, 1f) * shellRandomVelocity);

                Vector3 velocity = velocityDirection * shellVelocity;
                shellRB.AddForce(velocity + playerVelocity + randomVelocity, ForceMode.VelocityChange);

                Vector3 randomTorque = new Vector3(UnityEngine.Random.Range(-1f, 1f) * shellRandomTorque, UnityEngine.Random.Range(-1f, 1f) * shellRandomTorque, UnityEngine.Random.Range(-1f, 1f) * shellRandomTorque);

                shellRB.AddTorque(velocity * shellTorque, ForceMode.VelocityChange);
            }
        }
Esempio n. 29
0
        private static void ApplySpeedHacksOnSceneLoad()
        {
            Debug.Log("[SpeedHacks] Applying speed hacks...");

            var options = ConfigState.Instance.GetSpeedHacksOptions();

            if (options.DisableLights)
            {
                foreach (var light in CoreUtils.GetWorldRoot().GetComponentsInChildren <Light>())
                {
                    var el = light.GetComponent <SpeedHackExemptLight>();
                    if (el != null && el.AlwaysShowLight)
                    {
                        continue;
                    }

                    if (light.GetComponentInParent <BaseController>() != null)
                    {
                        continue;
                    }

                    light.enabled = false;
                }

                var lo = CoreUtils.GetWorldRoot().GetComponent <SpeedHackAmbientLightOverride>();
                if (lo != null)
                {
                    RenderSettings.ambientIntensity = lo.AmbientIntensity;
                    if (lo.OverrideColor)
                    {
                        RenderSettings.ambientMode  = UnityEngine.Rendering.AmbientMode.Flat;
                        RenderSettings.ambientLight = lo.AmbientColor;
                    }
                }
            }

            if (options.DisableShadows)
            {
                foreach (var light in CoreUtils.GetWorldRoot().GetComponentsInChildren <Light>())
                {
                    var el = light.GetComponent <SpeedHackExemptLight>();
                    if (el != null && el.AlwaysShowShadows)
                    {
                        continue;
                    }

                    if (light.GetComponentInParent <BaseController>() != null)
                    {
                        continue;
                    }

                    light.shadows = LightShadows.None;
                }
            }

            if (options.DisableBackgroundObjects)
            {
                foreach (var s in CoreUtils.GetWorldRoot().GetComponentsInChildren <SpeedHackBackgroundObject>(true))
                {
                    s.gameObject.SetActive(false);
                }
            }

            if (options.DisableDetailObjects)
            {
                foreach (var s in CoreUtils.GetWorldRoot().GetComponentsInChildren <SpeedHackDetailObject>(true))
                {
                    s.gameObject.SetActive(false);
                }
            }

            if (options.ReduceTerrainDetails)
            {
                foreach (var terrain in CoreUtils.GetWorldRoot().GetComponentsInChildren <Terrain>(true))
                {
                    terrain.shadowCastingMode        = UnityEngine.Rendering.ShadowCastingMode.Off;
                    terrain.detailObjectDensity     /= 2f;
                    terrain.detailObjectDistance    /= 2f;
                    terrain.treeBillboardDistance   /= 2f;
                    terrain.treeDistance            /= 2f;
                    terrain.treeMaximumFullLODCount /= 2;
                }
            }

            Debug.Log("...done!");
        }