示例#1
0
 void Awake()
 {
     particles      = GetComponent <ParticleSystem>();
     particleRate   = ParticleHelper.getEmissionRate(particles);
     spriteRenderer = GetComponent <SpriteRenderer>();
     ParticleHelper.setEmissionRate(particles, 0f);
 }
示例#2
0
        private void InitializeEmitterTesting()
        {
            List <Particle> particles = new List <Particle>();

            emitterTestingRoom = new EmitterTestingRoom();
            particleHelper     = new ParticleHelper(particles);
        }
示例#3
0
    void lookAtFood()
    {
        Vector3 foodPosition = food.transform.position;

        float angle    = ((Vector2)(transform.position - foodPosition)).getAngle() * Mathf.Deg2Rad,
              distance = ((Vector2)(transform.position - foodPosition)).magnitude;

        transform.rotation = Quaternion.Euler(0f, 0f, angle * Mathf.Rad2Deg);

        distance /= transform.localScale.x / 2f;

        mouthAngle = Mathf.Lerp(maxMouthAngle, 0f, distance / mouthStartDistance);
        updateMouth();

        bool flipped = foodPosition.x > transform.position.x;

        transform.localScale = new Vector3(1f, flipped ? -1f : 1f, 1f);


        if (distance <= eatRadius)
        {
            food.eaten   = true;
            mouthClosing = true;

            ParticleHelper.setEmissionRate(food.GetComponent <ParticleSystem>(), food.particleRate);

            MicrogameController.instance.setVictory(true, true);
            confettiParticles.Play();

            MicrogameController.instance.playSFX(victoryClip, 0f, 1f, .75f);
        }
    }
示例#4
0
    void Start()
    {
        BattleFactory.AddUnitToLayer(gameObject, layer);

        lifeCycleSec = ParticleHelper.GetlifeCycleSec(transform);
        if (lifeCycleSec < 0)
        {
            isLoop = true;
        }
    }
    private int GetDynamicLod(int lod, bool isParticle)
    {
        if (!this.m_dynamicLOD || !isParticle || lod == 2 || this.LIMIT_CONFIG == null || lod >= this.LIMIT_CONFIG.Length || lod < 0)
        {
            return(lod);
        }
        int particleActiveNumber = ParticleHelper.GetParticleActiveNumber();

        if (particleActiveNumber >= this.LIMIT_CONFIG[lod])
        {
            return(2);
        }
        return(lod);
    }
示例#6
0
    public static void displayIndicator(GameObject obj)
    {
        Vector3    rayStart = obj.transform.position + new Vector3(0, 80f, 0);
        RaycastHit hit;

        Physics.Raycast(rayStart, Vector3.down, out hit, 80f);

        var   part      = GameObject.Instantiate(ParticleHelper.getInstance().salvageParticles, hit.point, Quaternion.identity, obj.transform);
        float totalTime = obj.GetComponent <Structure>().getHP().HP;

        totalTime /= 2.5f;
        Debug.Log("Total time of salvage particle: " + totalTime);
        part.GetComponent <ParticleUVOffset>().totalTime = totalTime;
    }
示例#7
0
    private void Update()
    {
        this.m_timer += Time.deltaTime;
        if (this.m_timer > this.m_lifeTime)
        {
            base.gameObject.transform.position = new Vector3(10000f, 10000f, 10000f);
            Singleton <CGameObjectPool> .GetInstance().RecycleGameObject(base.gameObject);

            if (this.m_needRecordNumber)
            {
                ParticleHelper.DecParticleActiveNumber();
            }
        }
    }
        public IEnumerable <KeyValuePair <DateTime, Tuple <Normal, Normal> > > BatchRun(List <Tuple <DateTime, Point> > meas, Point initialPoint)
        {
            ParticleFilterSharp2D FilterSharp = new ParticleFilterSharp2D();

            IContinuousDistribution xDistribution = null;
            IContinuousDistribution yDistribution = null;
            IContinuousDistribution oDistribution = null;
            IContinuousDistribution vDistribution = null;


            if (initialPoint == null)
            {
                xDistribution = new ContinuousUniform(-10, 10);
                yDistribution = new ContinuousUniform(-10, 10);
                oDistribution = new ContinuousUniform(0, 2 * Math.PI);
                vDistribution = new ContinuousUniform(0.000001, 0.000001);
            }
            FilterSharp.Particles = ParticleFactory.BuildSwarm(N, xDistribution, yDistribution, vDistribution, oDistribution).ToList();



            DateTime dt = meas[0].Item1.AddTicks(-(long)meas.Select(_ => (double)_.Item1.Ticks).ToArray().SelectDifferences().Average());



            for (int i = 0; i < meas.Count(); i++)
            {
                long ticks = (meas[i].Item1 - dt).Ticks;

                // move based on last measurement

                FilterSharp.Predict(EffectiveCountMinRatio);
                var est = ParticleHelper.Estimate(FilterSharp.Particles);
                yield return(new KeyValuePair <DateTime, Tuple <Normal, Normal> >(dt, est));

                // predictions.Add(new KeyValuePair<DateTime, List<Point>>(dt, particles.Select(_=>(Point)(_)).ToList()));


                // incorporate measurements
                FilterSharp.Update(meas[i].Item2);


                dt = meas[i].Item1;
            }
        }
示例#9
0
    private int GetDynamicLod(int lod, bool isParticle)
    {
        if ((!this.m_dynamicLOD || !isParticle) || (lod == 2))
        {
            return(lod);
        }
        int particleActiveNumber = ParticleHelper.GetParticleActiveNumber();

        if (particleActiveNumber >= this.LIMIT_CONFIG[lod][1])
        {
            return(2);
        }
        if (particleActiveNumber >= this.LIMIT_CONFIG[lod][0])
        {
            return(1);
        }
        return(0);
    }
示例#10
0
    public new void handleDeserialization(SaveLoad.SerializationInfo info)
    {
        serializationData data = (serializationData)info;

        this.storedEnergy = data.storedEnergy;
        this.busy         = data.busy;
        this.ownResource  = data.ownResource;
        this.salvaging    = data.salvaging;
        this.curTarget    = data.target;

        if (salvaging)
        {
            Debug.Log("got salvaging info, creating particles....");
            //TODO, this gets called before terrain scripts are loaded
            GameObject.Instantiate(ParticleHelper.getInstance().salvageParticles, this.gameObject.transform);
        }

        //reloadConnections();
    }
示例#11
0
    void lookAtCursor()
    {
        Vector3 cursorPosition = CameraHelper.getCursorPosition();

        float angle    = MathHelper.getVectorAngle2D((Vector2)(transform.position - cursorPosition)) * Mathf.Deg2Rad,
              distance = ((Vector2)(transform.position - cursorPosition)).magnitude;

        transform.rotation = Quaternion.Euler(0f, 0f, angle * Mathf.Rad2Deg);

        distance /= transform.localScale.x / 2f;

        mouthAngle = Mathf.Lerp(maxMouthAngle, 0f, distance / mouthStartDistance);
        updateMouth();

        bool flipped = cursorPosition.x > transform.position.x;

        if (flipped)
        {
            transform.localScale = new Vector3(1f, -1f, 1f);
        }
        else
        {
            transform.localScale = new Vector3(1f, 1f, 1f);
        }

        if (distance <= eatRadius)
        {
            food.eaten   = true;
            mouthClosing = true;

            ParticleHelper.setEmissionRate(food.GetComponent <ParticleSystem>(), food.particleRate);

            //food.GetComponent<ParticleSystem>().emission.rate = new ParticleSystem.MinMaxCurve(food.particleRate);

            MicrogameController.instance.setVictory(true, true);

            //feedSound.pitch = 1.1f * Time.timeScale;
            //feedSound.Play();

            //CameraController.instance.setShakeCoolRate(0f);
            //CameraController.instance.setScreenShake(1f);
        }
    }
示例#12
0
    public new void handleDeserialization(SaveLoad.SerializationInfo info)
    {
        serializationData data = (serializationData)info;

        this.storedEnergy = data.storedEnergy;
        this.busy         = data.busy;
        this.ownResource  = data.ownResource;
        this.salvaging    = data.salvaging;
        if (this.busy)
        {
            DeliveryRoutes.addRoute(this.gameObject, DeliveryRoutes.getClosest("dropBase", this.gameObject).gameObject, ressources.Trees);
        }

        if (salvaging)
        {
            GameObject.Instantiate(ParticleHelper.getInstance().salvageParticles, this.gameObject.transform);
        }

        //reloadConnections();
    }
示例#13
0
        private void InitializeGameplay()
        {
            heightDisplay = new HeightDisplay();
            player        = new Player(heightDisplay);
            lava          = new Lava(GraphicsDevice);
            background    = new Background();

            List <Platform> platforms = new List <Platform>();
            List <Hazard>   hazards   = new List <Hazard>();
            List <Particle> particles = new List <Particle>();

            platformHelper  = new PlatformHelper(platforms, lava);
            collisionHelper = new CollisionHelper(player, lava, platforms, hazards);
            particleHelper  = new ParticleHelper(particles);

            Platform.Initialize(hazards);
            ParticleFactory.Initialize(particles);

            SimpleEvent.AddEvent(EventTypes.RESET, null);
        }
    // 播放粒子效果
    IEnumerator PlayEffect(GameObject go)
    {
        go = go.GetComponent <FormationDragItemUI> ().attachSlotUI.gameObject;
        GameObject prefab      = Resources.Load(DUST_PARTICLE_PATH) as GameObject;
        GameObject instanceObj = NGUITools.AddChild(go,prefab);

        instanceObj.transform.localScale = AppConfig.UNITY_SCALE_UI;

        battlePanel.particleList.Add(instanceObj);

        float leftTime = ParticleHelper.GetlifeCycleSec(instanceObj.transform);

        yield return(new WaitForSeconds(leftTime));

        if (instanceObj != null)
        {
            battlePanel.particleList.Remove(instanceObj);
            DestroyImmediate(instanceObj);
        }
    }
示例#15
0
    private int GetDynamicLod(int lod, bool isParticle)
    {
        if (((!this.m_dynamicLOD || !isParticle) || ((lod == 2) || (this.LIMIT_CONFIG == null))) || ((lod >= this.LIMIT_CONFIG.Length) || (lod < 0)))
        {
            return(lod);
        }
        int[] numArray = this.LIMIT_CONFIG[lod];
        if (numArray == null)
        {
            return(lod);
        }
        int particleActiveNumber = ParticleHelper.GetParticleActiveNumber();

        if (particleActiveNumber >= numArray[1])
        {
            return(2);
        }
        if (particleActiveNumber >= numArray[0])
        {
            return(1);
        }
        return(0);
    }
    // 播放粒子效果
    IEnumerator PlayEffect(string name, Vector3 v)
    {
        string DUST_PARTICLE_PATH = "profab/ui/effect/" + name;

        GameObject parent      = this.gameObject;
        GameObject instanceObj = ResourceHelper.Load(DUST_PARTICLE_PATH);

        Vector3 ui_world_pos = transform.TransformPoint(v);

        instanceObj.transform.localPosition = ui_world_pos;
        instanceObj.transform.parent        = transform;

        // 添加粒子对象到UI管理容器
        UIParticleManager.instance.AddParticle(instanceObj);

        float leftTime = ParticleHelper.GetlifeCycleSec(instanceObj.transform);

        yield return(new WaitForSeconds(leftTime));

        if (instanceObj != null)
        {
            DestroyImmediate(instanceObj);
        }
    }
示例#17
0
        /// <summary>
        /// Called when the window is loading, only to be used by the startup process.
        /// </summary>
        void Window_Load(object sender, EventArgs e)
        {
            SysConsole.Output(OutputType.CLIENTINIT, "Window generated!");
            DPIScale = Window.Width / CVars.r_width.ValueF;
            SysConsole.Output(OutputType.CLIENTINIT, "DPIScale is " + DPIScale + "!");
            SysConsole.Output(OutputType.CLIENTINIT, "Setting up a game engine backend placeholder...");
            FakeEngine();
            SysConsole.Output(OutputType.CLIENTINIT, "Loading base textures...");
            PreInitRendering();
            Textures = new TextureEngine();
            Textures.InitTextureSystem(Files);
            ItemFrame        = Textures.GetTexture("ui/hud/item_frame");
            CWindow.Textures = Textures;
            SysConsole.Output(OutputType.CLIENTINIT, "Loading shaders...");
            Shaders    = new ShaderEngine();
            GLVendor   = GL.GetString(StringName.Vendor);
            GLVersion  = GL.GetString(StringName.Version);
            GLRenderer = GL.GetString(StringName.Renderer);
            SysConsole.Output(OutputType.CLIENTINIT, "Vendor: " + GLVendor + ", GLVersion: " + GLVersion + ", Renderer: " + GLRenderer);
            if (GLVendor.ToLowerFast().Contains("intel"))
            {
                SysConsole.Output(OutputType.CLIENTINIT, "Disabling good graphics (Appears to be Intel: '" + GLVendor + "')");
                Shaders.MCM_GOOD_GRAPHICS = false;
            }
            Shaders.InitShaderSystem();
            CWindow.Shaders = Shaders;
            Engine.GetShaders();
            GraphicsUtil.CheckError("Load - Shaders");
            SysConsole.Output(OutputType.CLIENTINIT, "Loading animation engine...");
            Animations         = new AnimationEngine();
            CWindow.Animations = Animations;
            SysConsole.Output(OutputType.CLIENTINIT, "Loading model engine...");
            Models = new ModelEngine();
            Models.Init(Animations, CWindow);
            LODHelp        = new ModelLODHelper(this);
            CWindow.Models = Models;
            SysConsole.Output(OutputType.CLIENTINIT, "Loading rendering helper...");
            Rendering = new Renderer(Textures, Shaders, Models);
            Rendering.Init();
            CWindow.Rendering3D = Rendering;
            CWindow.Rendering2D = new Renderer2D(Textures, Shaders);
            CWindow.Rendering2D.Init();
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing load screen...");
            load_screen = Textures.GetTexture("ui/menus/loadscreen");
            Establish2D();
            SWLoading.Start();
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Loading block textures...");
            TBlock = new TextureBlock();
            TBlock.Generate(this, CVars, Textures, false);
            GraphicsUtil.CheckError("Load - Textures");
            SysConsole.Output(OutputType.CLIENTINIT, "Loading fonts...");
            Fonts = new GLFontEngine(Textures, Shaders);
            Fonts.Init(Files);
            FontSets = new FontSetEngine(Fonts);
            FontSets.Init((subdat) => Languages.GetText(Files, subdat), () => Ortho, () => GlobalTickTimeLocal);
            GraphicsUtil.CheckError("Load - Fonts");
            PassLoadScreen();
            CWindow.FontSets = FontSets;
            CWindow.GLFonts  = Fonts;
            SysConsole.Output(OutputType.CLIENTINIT, "Loading general graphics settings...");
            CVars.r_vsync.OnChanged += OnVsyncChanged;
            OnVsyncChanged(CVars.r_vsync, EventArgs.Empty);
            CVars.r_cloudshadows.OnChanged += OnCloudShadowChanged;
            CVars.r_transpll.OnChanged     += OnLLChanged;
            OnLLChanged(CVars.r_transpll, EventArgs.Empty);
            GraphicsUtil.CheckError("Load - General Graphics");
            SysConsole.Output(OutputType.CLIENTINIT, "Loading UI engine...");
            UIConsole.InitConsole(); // TODO: make this non-static
            InitChatSystem();
            PassLoadScreen();
            GraphicsUtil.CheckError("Load - UI");
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing rendering engine...");
            InitRendering();
            GraphicsUtil.CheckError("Load - Rendering");
            SysConsole.Output(OutputType.CLIENTINIT, "Loading particle effect engine...");
            Particles = new ParticleHelper(this)
            {
                Engine = new ParticleEngine(this)
            };
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing mouse and keyboard handlers...");
            KeyHandler.Init();
            Gamepad = new GamePadHandler();
            Gamepad.Init(this);
            PassLoadScreen();
            GraphicsUtil.CheckError("Load - Keyboard/mouse");
            SysConsole.Output(OutputType.CLIENTINIT, "Building the sound system...");
            Sounds.Init(Engine);
            GraphicsUtil.CheckError("Load - Sound");
            SysConsole.Output(OutputType.CLIENTINIT, "Building game world...");
            BuildWorld();
            PassLoadScreen();
            GraphicsUtil.CheckError("Load - World");
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing networking...");
            Network = new NetworkBase(this);
            RegisterDefaultEntityTypes();
            GraphicsUtil.CheckError("Load - Net");
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Loading Voxel computer...");
            try
            {
                VoxelComputer = new VoxelComputeEngine();
                VoxelComputer.Init(this);
            }
            catch (Exception ex)
            {
                SysConsole.Output(ex);
            }
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Playing background music...");
            BackgroundMusic();
            CVars.a_musicvolume.OnChanged += OnMusicVolumeChanged;
            CVars.a_musicpitch.OnChanged  += OnMusicPitchChanged;
            CVars.a_music.OnChanged       += OnMusicChanged;
            CVars.a_echovolume.OnChanged  += OnEchoVolumeChanged;
            OnEchoVolumeChanged(null, null);
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Setting up screens...");
            TheMainMenuScreen         = new MainMenuScreen(this);
            TheGameScreen             = new GameScreen(this);
            TheSingleplayerMenuScreen = new SingleplayerMenuScreen(this);
            TheLoadScreen             = new LoadScreen(this);
            CScreen = TheMainMenuScreen;
            SysConsole.Output(OutputType.CLIENTINIT, "Trying to grab RawGamePad...");
            try
            {
                RawGamePad = new XInput();
            }
            catch (Exception ex)
            {
                SysConsole.Output(OutputType.CLIENTINIT, "Failed to grab RawGamePad: " + ex.Message);
            }
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing inventory...");
            InitInventory();
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Creating sky...");
            CreateSkyBox();
            SysConsole.Output(OutputType.CLIENTINIT, "Requesting a menu server...");
            LocalServer?.ShutDown();
            LocalServer = new Server(28009)
            {
                IsMenu = true
            };                                                 // TODO: Grab first free port?
            Object locky = new Object();
            bool   ready = false;

            Schedule.StartAsyncTask(() =>
            {
                LocalServer.StartUp("menu", () =>
                {
                    lock (locky)
                    {
                        ready = true;
                    }
                });
            });
            while (true)
            {
                lock (locky)
                {
                    if (ready)
                    {
                        break;
                    }
                }
                PassLoadScreen();
                Thread.Sleep(50);
            }
            SysConsole.Output(OutputType.CLIENTINIT, "Connecting to a menu server...");
            Network.LastConnectionFailed = false;
            Network.Connect("localhost", "28009", true, null); // TODO: Grab accurate local IP?
            Stopwatch sw = new Stopwatch();

            sw.Start();
            bool annc = false;

            while (true)
            {
                if (Network.LastConnectionFailed)
                {
                    SysConsole.Output(OutputType.CLIENTINIT, "Failed to connect to menu server! Failing!");
                    Window.Close();
                    return;
                }
                if (Network.IsAlive)
                {
                    break;
                }
                sw.Stop();
                long ms = sw.ElapsedMilliseconds;
                sw.Start();
                if (ms > 10000 && !annc)
                {
                    annc = true;
                    SysConsole.Output(OutputType.WARNING, "Taking weirdly long, did something fail?!");
                }
                if (ms > 20000)
                {
                    SysConsole.Output(OutputType.CLIENTINIT, "Timed out while trying to connect to menu server! Failing!");
                    Window.Close();
                    return;
                }
                PassLoadScreen();
                Thread.Sleep(50);
            }
            SysConsole.Output(OutputType.CLIENTINIT, "Showing main menu...");
            ShowMainMenu();
            GraphicsUtil.CheckError("Load - Final");
            SysConsole.Output(OutputType.CLIENTINIT, "Ready and looping!");
        }
        public async Task CreateSceneAsync()
        {
            var canvas = await Canvas.GetElementById(
                "game-window"
                );

            var engine = await Engine.NewEngine(
                canvas,
                true
                );

            // This creates a basic Babylon Scene object (non-mesh)
            var scene = await Scene.NewScene(engine);

            await scene.set_clearColor(
                await Color4.NewColor4(
                    0.31m,
                    0.48m,
                    0.64m,
                    1
                    )
                );

            //add an arcRotateCamera to the scene
            var camera = await ArcRotateCamera.NewArcRotateCamera(
                "camera",
                await Tools.ToRadians(125),
                await Tools.ToRadians(70), 25,
                await Vector3.NewVector3(0, 3, 0),
                scene
                );

            await camera.set_lowerRadiusLimit(10);

            await camera.set_upperRadiusLimit(40);

            // This attaches the camera to the canvas
            await camera.attachControl(true);

            //array for holding the cannon and "paired" animation group
            var cannonAnimationPairings = new Dictionary <string, string>();

            //array for holding readyToPlay status for the cannons
            var cannonReadyToPlay = new Dictionary <string, int>();

            //Load the tower assets
            var pirateFortImportEntity = await SceneLoader.ImportMeshAsync(
                "",
                "https://models.babylonjs.com/pirateFort/",
                "pirateFort.glb",
                scene
                );

            var pirateFortImport = pirateFortImportEntity.ToEntity <SceneLoaderImportMeshEntity>();
            var meshes           = await pirateFortImport.get_meshes();

            await meshes[0].set_name("pirateFort");
            var   seaMesh = await scene.getMeshByName("sea");

            await(await seaMesh.get_material()).set_needDepthPrePass(true);
            await(await scene.getLightByName("Sun")).set_intensity(12);

            //Load the cannon model and create clones
            var cannonImportResult = (await SceneLoader.ImportMeshAsync(
                                          "",
                                          "https://models.babylonjs.com/pirateFort/",
                                          "cannon.glb",
                                          scene
                                          )).ToEntity <SceneLoaderImportMeshEntity>();
            //remove the top level root node
            var cannonMeshs = await cannonImportResult.get_meshes();

            var cannon = (await cannonMeshs[0].getChildren())[0];
            await cannon.setParent(null);

            await cannonMeshs[0].dispose();

            //set the metadata of each mesh to filter on later
            var cannonMeshes = await cannon.getChildMeshes();

            for (var i = 0; i < cannonMeshes.Length; i++)
            {
                var metadata = await NodeMetadata.NewNodeMetadata();

                await metadata.set_name("cannon");

                await cannonMeshes[i].set_metadata(metadata);
            }

            var importedAnimGroups = await cannonImportResult.get_animationGroups();

            //loop through all imported animation groups and copy the animation curve data to an array.
            var animations = new Animation[importedAnimGroups.Length];

            for (var i = 0; i < importedAnimGroups.Length; i++)
            {
                await importedAnimGroups[i].stop();
                animations[i] = await(await importedAnimGroups[i].get_targetedAnimations())[0].get_animation();
                await importedAnimGroups[i].dispose();
            }

            //create a new animation group and add targeted animations based on copied curve data from the "animations" array.
            var cannonAnimGroup = await AnimationGroup.NewAnimationGroup(
                "cannonAnimGroup"
                );

            await cannonAnimGroup.addTargetedAnimation(
                animations[0],
                (await cannon.getChildMeshes())[1]
                );

            await cannonAnimGroup.addTargetedAnimation(
                animations[1],
                (await cannon.getChildMeshes())[0]
                );

            //create a box for particle emission, position it at the muzzle of the cannon, turn off visibility and parent it to the cannon mesh
            var particleEmitter = await MeshBuilder.CreateBox(
                "particleEmitter",
                new { size = 0.05 },
                scene
                );

            await particleEmitter.set_position(await Vector3.NewVector3(
                                                   0,
                                                   0.76m,
                                                   1.05m
                                                   ));

            await(await particleEmitter.get_rotation()).set_x(await Tools.ToRadians(78.5m));
            await particleEmitter.set_isVisible(false);

            await particleEmitter.setParent(
                (await cannon.getChildMeshes())[1]
                );

            //load particle system from the snippet server and set the emitter to the particleEmitter. Set its stopDuration.
            var baseurl = await Tools.get_BaseUrl();

            var snippetUrl = await ParticleHelper.get_SnippetUrl();

            var smokeBlast = await ParticleHelper.CreateFromSnippetAsync(
                "LCBQ5Y#6",
                scene,
                false,
                await ParticleHelper.get_SnippetUrl()
                );

            await smokeBlast.set_emitter(particleEmitter);

            await smokeBlast.set_targetStopDuration(0.2m);

            //load a cannon blast sound
            var cannonBlastSound = await Sound.NewSound(
                "music",
                "https://assets.babylonjs.com/sound/cannonBlast.mp3",
                scene
                );

            //position and rotation data for the placement of the cannon clones
            var cannonPositionArray = new Vector3[][] {
                new Vector3[]
                {
                    await Vector3.NewVector3(0.97m, 5.52m, 1.79m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(0), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(1.08m, 2.32m, 3.05m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(0), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(1.46m, 2.35m, -0.73m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(90), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(1.45m, 5.52m, -1.66m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(90), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(1.49m, 8.69m, -0.35m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(90), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(-1.37m, 8.69m, -0.39m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(-90), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(0.58m, 4, -2.18m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(180), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(1.22m, 8.69m, -2.5m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(180), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(-1.31m, 2.33m, -2.45m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(180), await Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    await Vector3.NewVector3(-3.54m, 5.26m, -2.12m),
                    await Vector3.NewVector3(await Tools.ToRadians(0), await Tools.ToRadians(-90), await Tools.ToRadians(180))
                }
            };

            //create 10 cannon clones, each with unique position/rotation data. Note that particle systems are cloned with parent meshes
            //also create 10 new animation groups with targeted animations applied to the newly cloned meshes
            for (var i = 0; i < 10; i++)
            {
                var cannonClone = await cannon.clone <AbstractMesh>(
                    "cannonClone" + i
                    );

                await cannonClone.set_position(cannonPositionArray[i][0]);

                await cannonClone.set_rotation(cannonPositionArray[i][1]);

                var cannonAnimGroupClone = await AnimationGroup.NewAnimationGroup(
                    "cannonAnimGroupClone" + i
                    );

                await cannonAnimGroupClone.addTargetedAnimation(
                    await (await cannonAnimGroup.get_targetedAnimations())[0].get_animation(),
                    (await cannonClone.getChildMeshes())[1]);

                await cannonAnimGroupClone.addTargetedAnimation(
                    await (await cannonAnimGroup.get_targetedAnimations())[1].get_animation(),
                    (await cannonClone.getChildMeshes())[0]);

                //store a key/value pair of each clone name and the name of the associated animation group name.
                cannonAnimationPairings[await cannonClone.get_name()] = await cannonAnimGroupClone.get_name();

                //store key/value pair for the cannon name and it's readyToPlay status as 1;
                cannonReadyToPlay[await cannonClone.get_name()] = 1;
            }
            //dispose of the original cannon, animation group, and particle system
            await cannon.dispose();

            await cannonAnimGroup.dispose();

            await smokeBlast.dispose();

            //create an array for all particle systems in the scene, loop through it and stop all systems from playing.
            var smokeBlasts = await scene.get_particleSystems();

            for (var i = 0; i < smokeBlasts.Length; i++)
            {
                await smokeBlasts[i].stop();
            }

            //logic of what happens on a click
            await(await scene.get_onPointerObservable()).add(async(pointerInfo, eventState) =>
            {
                // PointerEventTypes.POINTERDOWN
                if (await pointerInfo.get_type() != 1)
                {
                    return;
                }
                var pickResult = await pointerInfo.get_pickInfo();
                //check if a mesh was picked and if that mesh has specific metadata
                var pickedMesh = await pickResult.get_pickedMesh();
                if (pickedMesh != null &&
                    await pickedMesh.get_metadata() != null)
                {
                    var metadataNode = (await pickedMesh.get_metadata()).ToEntity <NodeMetadata>();
                    if (await metadataNode.get_name() != "cannon")
                    {
                        return;
                    }
                    //find the top level parent (necessary since the cannon is an extra layer below the clone root)
                    var topParent = await(await pickResult.get_pickedMesh()).get_parent();
                    var parent    = await topParent.get_parent();
                    if (parent != null &&
                        await parent.get_name() != null)
                    {
                        topParent = parent;
                    }
                    var name = await topParent.get_name();
                    //wrap all 'play' elements into a check to make sure the cannon can be played.
                    if (cannonReadyToPlay[name] == 1)
                    {
                        //set the readyToPlay status to 0
                        cannonReadyToPlay[name] = 0;
                        //loop through all of the animation groups in the scene and play the correct group based on the top level parent of the picked mesh.
                        var animationToPlay = cannonAnimationPairings[name];
                        for (var i = 0; i < (await scene.get_animationGroups()).Length; i++)
                        {
                            if (await(await scene.get_animationGroups())[i].get_name() == animationToPlay)
                            {
                                await(await scene.get_animationGroups())[i].play();
                                //after the animation has finished, set the readyToPlay status for this cannon to 1;
                                await(await(await scene.get_animationGroups())[i].get_onAnimationGroupEndObservable()).addOnce(async(_, __) =>
                                {
                                    cannonReadyToPlay[await topParent.get_name()] = 1;
                                });
                            }
                        }
                        //loop through all particle systems in the scene, loop through all picked mesh submeshes. if there is a matching mesh and particle system emitter, start the particle system.
                        var childMeshes = await(await pickResult.get_pickedMesh()).getChildMeshes();
                        for (var i = 0; i < smokeBlasts.Length; i++)
                        {
                            for (var j = 0; j < childMeshes.Length; j++)
                            {
                                if (childMeshes[j].___guid == (await smokeBlasts[i].get_emitter()).___guid)
                                {
                                    await smokeBlasts[i].start();
                                }
                            }
                        }
                        await cannonBlastSound.play();
                    }
                }
            });
            //scene.onPointerDown = function(evt, pickResult) {
            //    //check if a mesh was picked and if that mesh has specific metadata
            //    if (pickResult.pickedMesh && pickResult.pickedMesh.metadata === "cannon")
            //    {
            //        //find the top level parent (necessary since the cannon is an extra layer below the clone root)
            //        var topParent = pickResult.pickedMesh.parent;
            //        if (topParent.parent)
            //        {
            //            topParent = topParent.parent;
            //        }

            //        //wrap all 'play' elements into a check to make sure the cannon can be played.
            //        if (cannonReadyToPlay[topParent.name] === 1)
            //        {
            //            //set the readyToPlay status to 0
            //            cannonReadyToPlay[topParent.name] = 0;
            //            //loop through all of the animation groups in the scene and play the correct group based on the top level parent of the picked mesh.
            //            var animationToPlay = cannonAnimationPairings[topParent.name];
            //            for (var i = 0; i < scene.animationGroups.length; i++)
            //            {
            //                if (scene.animationGroups[i].name === animationToPlay)
            //                {
            //                    scene.animationGroups[i].play();
            //                    //after the animation has finished, set the readyToPlay status for this cannon to 1;
            //                    scene.animationGroups[i].onAnimationGroupEndObservable.addOnce(() =>
            //                    {
            //                        cannonReadyToPlay[topParent.name] = 1;
            //                    });
            //                }
            //            }
            //            //loop through all particle systems in the scene, loop through all picked mesh submeshes. if there is a matching mesh and particle system emitter, start the particle system.
            //            var childMeshes = pickResult.pickedMesh.getChildMeshes();
            //            for (var i = 0; i < smokeBlasts.length; i++)
            //            {
            //                for (var j = 0; j < childMeshes.length; j++)
            //                {
            //                    if (childMeshes[j] === smokeBlasts[i].emitter)
            //                    {
            //                        smokeBlasts[i].start();
            //                    }
            //                }
            //            }
            //            cannonBlastSound.play();
            //        }
            //    }
            //};

            _scene = scene;
            await _scene.set_activeCamera(camera);

            await engine.runRenderLoop(new ActionCallback(
                                           () => Task.Run(() => _scene.render(true, false))
                                           ));

            _engine = engine;
        }
示例#19
0
        /// <summary>
        /// Called when the window is loading, only to be used by the startup process.
        /// </summary>
        void Window_Load(object sender, EventArgs e)
        {
            SysConsole.Output(OutputType.INIT, "Window generated!");
            DPIScale = Window.Width / CVars.r_width.ValueF;
            SysConsole.Output(OutputType.INIT, "DPIScale is " + DPIScale + "!");
            SysConsole.Output(OutputType.INIT, "Loading base textures...");
            PreInitRendering();
            Textures = new TextureEngine();
            Textures.InitTextureSystem(this);
            ItemFrame = Textures.GetTexture("ui/hud/item_frame");
            SysConsole.Output(OutputType.INIT, "Loading shaders...");
            Shaders  = new ShaderEngine();
            GLVendor = GL.GetString(StringName.Vendor);
            CVars.s_glvendor.Value = GLVendor;
            GLVersion = GL.GetString(StringName.Version);
            CVars.s_glversion.Value = GLVersion;
            GLRenderer = GL.GetString(StringName.Renderer);
            CVars.s_glrenderer.Value = GLRenderer;
            SysConsole.Output(OutputType.INIT, "Vendor: " + GLVendor + ", GLVersion: " + GLVersion + ", Renderer: " + GLRenderer);
            if (GLVendor.ToLowerFast().Contains("intel"))
            {
                SysConsole.Output(OutputType.INIT, "Disabling good graphics (Appears to be Intel: '" + GLVendor + "')");
                Shaders.MCM_GOOD_GRAPHICS = false;
            }
            Shaders.InitShaderSystem(this);
            View3D.CheckError("Load - Shaders");
            SysConsole.Output(OutputType.INIT, "Loading rendering helper...");
            Rendering = new Renderer(Textures, Shaders);
            Rendering.Init();
            SysConsole.Output(OutputType.INIT, "Preparing load screen...");
            Texture load_screen = Textures.GetTexture("ui/menus/loadscreen");

            load_screen.Bind();
            Shaders.ColorMultShader.Bind();
            Establish2D();
            Rendering.RenderRectangle(0, 0, Window.Width, Window.Height);
            Window.SwapBuffers();
            SysConsole.Output(OutputType.INIT, "Loading block textures...");
            TBlock = new TextureBlock();
            TBlock.Generate(this, CVars, Textures);
            View3D.CheckError("Load - Textures");
            SysConsole.Output(OutputType.INIT, "Loading fonts...");
            Fonts = new GLFontEngine(Shaders);
            Fonts.Init(this);
            FontSets = new FontSetEngine(Fonts);
            FontSets.Init(this);
            View3D.CheckError("Load - Fonts");
            SysConsole.Output(OutputType.INIT, "Loading animation engine...");
            Animations = new AnimationEngine();
            SysConsole.Output(OutputType.INIT, "Loading model engine...");
            Models = new ModelEngine();
            Models.Init(Animations, this);
            SysConsole.Output(OutputType.INIT, "Loading general graphics settings...");
            CVars.r_vsync.OnChanged += onVsyncChanged;
            onVsyncChanged(CVars.r_vsync, null);
            CVars.r_cloudshadows.OnChanged += onCloudShadowChanged;
            View3D.CheckError("Load - General Graphics");
            SysConsole.Output(OutputType.INIT, "Loading UI engine...");
            UIConsole.InitConsole(); // TODO: make this non-static
            InitChatSystem();
            View3D.CheckError("Load - UI");
            SysConsole.Output(OutputType.INIT, "Preparing rendering engine...");
            InitRendering();
            View3D.CheckError("Load - Rendering");
            SysConsole.Output(OutputType.INIT, "Loading particle effect engine...");
            Particles = new ParticleHelper(this)
            {
                Engine = new ParticleEngine(this)
            };
            SysConsole.Output(OutputType.INIT, "Preparing mouse, keyboard, and gamepad handlers...");
            KeyHandler.Init();
            GamePadHandler.Init();
            View3D.CheckError("Load - Keyboard/mouse");
            SysConsole.Output(OutputType.INIT, "Building the sound system...");
            Sounds = new SoundEngine();
            Sounds.Init(this, CVars);
            View3D.CheckError("Load - Sound");
            SysConsole.Output(OutputType.INIT, "Building game world...");
            BuildWorld();
            View3D.CheckError("Load - World");
            SysConsole.Output(OutputType.INIT, "Preparing networking...");
            Network = new NetworkBase(this);
            RegisterDefaultEntityTypes();
            View3D.CheckError("Load - Net");
            SysConsole.Output(OutputType.INIT, "Playing background music...");
            BackgroundMusic();
            CVars.a_musicvolume.OnChanged += onMusicVolumeChanged;
            CVars.a_musicpitch.OnChanged  += onMusicPitchChanged;
            CVars.a_music.OnChanged       += onMusicChanged;
            CVars.a_echovolume.OnChanged  += OnEchoVolumeChanged;
            OnEchoVolumeChanged(null, null);
            SysConsole.Output(OutputType.INIT, "Setting up screens...");
            TheMainMenuScreen         = new MainMenuScreen(this);
            TheGameScreen             = new GameScreen(this);
            TheSingleplayerMenuScreen = new SingleplayerMenuScreen(this);
            SysConsole.Output(OutputType.INIT, "Preparing inventory...");
            InitInventory();
            SysConsole.Output(OutputType.INIT, "Showing main menu...");
            ShowMainMenu();
            SysConsole.Output(OutputType.INIT, "Trying to grab RawGamePad...");
            try
            {
                RawGamePad = new XInput();
            }
            catch (Exception ex)
            {
                SysConsole.Output(OutputType.INIT, "Failed to grab RawGamePad: " + ex.Message);
            }
            View3D.CheckError("Load - Final");
            SysConsole.Output(OutputType.INIT, "Ready and looping!");
        }
示例#20
0
 // Use this for initialization
 void Start()
 {
     instance = this;
 }