Пример #1
0
    public void setIngameObjects(GameObject parentObject)
    {
        ingameObjectParent = parentObject;
        objects            = new List <List <InGameObject> >();
        _objectCounts      = new List <List <int> >();
        for (int i = 0; i < objectGroups.Count; i++)
        {
            objects.Add(new List <InGameObject>());
            _objectCounts.Add(new List <int>());
        }

        for (int i = 0; i < parentObject.transform.childCount; i++)
        {
            if (parentObject.transform.GetChild(i).GetComponent <InGameObject>() != null)
            {
                InGameObject cursor = parentObject.transform.GetChild(i).GetComponent <InGameObject>();
                cursor.boundaries = ingameObjectParent.GetComponent <BoundingBoxCalculator>().platformBounds[i];
                if (objectGroups.Contains(cursor.type))
                {
                    objects[objectGroups.IndexOf(cursor.type)].Add(cursor);
                    _objectCounts[objectGroups.IndexOf(cursor.type)].Add(0);
                }
            }
        }
    }
Пример #2
0
    private Transform CreateBlock(int value, int xPos, int yPos, int zPos)
    {
        // The transform to create
        Transform toCreate = null;

        // Return on invalid positions
        // Set the value for the internal level representation
        // If the value is not empty, set it to the correct tile
        if (value != -1)
        {
            toCreate = tiles[value];
        }
        if (toCreate != null)
        {
            //Create the object we want to create
            Transform newObject = Instantiate(toCreate, new Vector3(xPos, yPos, toCreate.position.z), Quaternion.identity) as Transform;
            if (newObject.GetComponent <InGameObject>() != null)
            {
                InGameObject inObj = newObject.GetComponent <InGameObject>();
                inObj.SetSortingOrder();
                inObj.ActivateThreshold = previewThreshold;
                inObj.CurrentStatus     = previewStatus;
            }
            //Give the new object the same name as our tile prefab
            newObject.name = toCreate.name;
            // Set the object's parent to the layer parent variable so it doesn't clutter our Hierarchy
            newObject.parent = GetLayerParent(zPos).transform;
            // Add the new object to the gameObjects array for correct administration
            return(newObject);
        }
        return(null);
    }
Пример #3
0
    public Component getNextComponent(Type t)
    {
        Component result = null;

        ///check if components of this type were requested before
        if (UnrecycledComponents.ContainsKey(t))
        {
            List <Component> components = unrecycledComponents[t];
            ///if a component is assigned to a restorable script it is removed
            ///from the unused component list
            if (components.Count > 0)
            {
                result = components[0];
                components.RemoveAt(0);
            }
        }
        else
        {
            List <Component> components = InGameObject.GetComponents(t).ToList();
            if (components.Count > 0)
            {
                result = components[0];
                components.RemoveAt(0);
            }
            unrecycledComponents.Add(t, components);
        }
        ///if the component could not be recycled it is created
        if (result == null)
        {
            result = InGameObject.AddComponent(t);
        }
        return(result);
    }
Пример #4
0
    public T getComponent <T>() where T : Component
    {
        T    result = null;
        Type t      = typeof(T);

        ///check if components of this type were requested before
        if (AlreadyRestoredComponents.ContainsKey(t))
        {
            List <Component> components = alreadyRestoredComponents[t];
            ///if a component is assigned to a saveable object it is removed
            ///from the unused component list
            if (components.Count > 0)
            {
                result = (T)components[0];
                components.RemoveAt(0);
            }
        }
        else
        {
            List <Component> components = InGameObject.GetComponents(t).ToList();
            if (components.Count > 0)
            {
                result = (T)components[0];
                components.RemoveAt(0);
            }
            alreadyRestoredComponents.Add(t, components);
        }
        return(result);
    }
Пример #5
0
    public void DeactivateObject(InGameObject gameObject)
    {
        int index = objectGroupNames.IndexOf(gameObject.type);

        gameObject.enabled = false;
        _pools[index].Enqueue(gameObject);
    }
Пример #6
0
        private static void InGameObject_OnCreate(InGameObject inGameObject)
        {
            if (!_logEnabled)
            {
                return;
            }
            var baseTypes = inGameObject.GetBaseTypes().ToArray();

            if (!baseTypes.Contains("BaseObject"))
            {
                return;
            }
            var baseObj = inGameObject.Get <BaseGameObject>();

            if (_onlyLogLocal && baseObj != null && baseObj.Owner != LocalPlayer.Instance)
            {
                return;
            }
            Console.WriteLine("New Object:");
            Console.WriteLine("Name: " + inGameObject.ObjectName);
            foreach (var baseType in baseTypes)
            {
                Console.WriteLine(baseType);
            }
            Console.WriteLine("----");
            if (baseTypes.Contains("Throw"))
            {
                var throwObj = inGameObject.Get <ThrowObject>();
                Console.WriteLine("Distance: " + throwObj.StartPosition.Distance(throwObj.TargetPosition));
                Console.WriteLine("Duration: " + throwObj.Duration);
                Console.WriteLine("MapColRadius: " + throwObj.MapCollisionRadius);
                Console.WriteLine("SpellRadius: " + throwObj.SpellCollisionRadius);
                Console.WriteLine("----");
            }
        }
Пример #7
0
                private static void InGameObject_OnCreate(InGameObject inGameObject)
                {
                    var baseTypes = inGameObject.GetBaseTypes().ToArray();

                    if (baseTypes.Contains("CurveProjectile") || baseTypes.Contains("CurveProjectile2"))
                    {
                        var data = AbilityDatabase.Get(inGameObject.ObjectName);
                        if (data == null)
                        {
                            return;
                        }
                        var pos        = LocalPlayer.Instance.Pos();
                        var projectile = inGameObject.Get <CurveProjectileObject>();

                        var closest = GeometryLib.NearestPointOnFiniteLine(projectile.Position,
                                                                           projectile.TargetPosition, pos);
                        if (pos.Distance(closest) > 6)
                        {
                            return;
                        }

                        var tp = new TrackedCurveProjectile(projectile, data);
                        AddAfterFrame.Add(tp);
                    }
                }
Пример #8
0
        private static void HealSelf()
        {
            InGameObject cloneToUse = null;

            if (UltiClone != null && ZanderHero.Distance(UltiClone.Get <MapGameObject>().Position) <= M1Range)
            {
                cloneToUse = UltiClone;
            }
            else if (EX2Clone != null && ZanderHero.Distance(EX2Clone.Get <MapGameObject>().Position) <= M1Range)
            {
                cloneToUse = EX2Clone;
            }
            else if (SpaceClone != null && ZanderHero.Distance(SpaceClone.Get <MapGameObject>().Position) <= M1Range)
            {
                cloneToUse = SpaceClone;
            }

            if (cloneToUse != null)
            {
                LocalPlayer.EditAimPosition = true;
                var pred = TestPrediction.GetNormalLinePrediction(cloneToUse.Get <MapGameObject>().Position, ZanderHero, M1Range, M1Speed, M1Radius, true);
                if (pred.CanHit && MiscUtils.CanCast(AbilitySlot.Ability1))
                {
                    LocalPlayer.Aim(pred.CastPosition);
                    LocalPlayer.PressAbility(AbilitySlot.Ability1, true);
                }
            }
        }
Пример #9
0
        private static void OnCreateHandler(InGameObject gameObject)
        {
            if (gameObject == null)
            {
                Console.WriteLine("[AbilityTracker#OnCreateHandler] GameObject is null, please report this to Hoyer");
                return;
            }

            if (LocalPlayer.Instance == null)
            {
                Console.WriteLine("[AbilityTracker#OnCreateHandler] LocalPlayer is null, please report this to Hoyer");
                return;
            }

            var baseTypes = gameObject.GetBaseTypes();

            if (!baseTypes.Contains("BaseObject"))
            {
                return;
            }
            var baseObj = gameObject.Get <BaseGameObject>();

            if (baseObj != null && baseObj.TeamId != LocalPlayer.Instance.BaseObject.TeamId)
            {
                EnemyObjectSpawn.Invoke(gameObject);
            }
        }
Пример #10
0
        private static void OnDestroy(InGameObject inGameObject)
        {
            if (_devMenu.GetBoolean("obj.destroy"))
            {
                Console.WriteLine(inGameObject.ObjectName + " of type " + inGameObject.GetType().ToString() + " destroyed");
            }

            var proj = inGameObject as Projectile;

            if (proj != null && proj.BaseObject.TeamId == DevHero.BaseObject.TeamId)
            {
                if (ProjSpeedSW.IsRunning && proj.IsSame(LastProj))
                {
                    ProjSpeedSW.Stop();

                    LastProj = null;

                    var distance = proj.CalculatedEndPosition.Distance(proj.StartPosition);
                    var time     = ProjSpeedSW.Elapsed.TotalSeconds;

                    var speed = distance / time;
                    Console.WriteLine("Speed: " + speed);
                }
            }
        }
Пример #11
0
        private void OnCreate(InGameObject inGameObject)
        {
            if (!Game.IsInGame)
            {
                return;
            }

            if (ZanderHero.CharName != "Zander")
            {
                return;
            }

            var baseObject = inGameObject.Get <BaseGameObject>();

            if (baseObject != null && baseObject.TeamId == ZanderHero.BaseObject.TeamId)
            {
                if (inGameObject.ObjectName.Equals(SpaceCloneName))
                {
                    SpaceClone = inGameObject;
                }
                else if (inGameObject.ObjectName.Equals(EX2CloneName))
                {
                    EX2Clone = inGameObject;
                }
                else if (inGameObject.ObjectName.Equals(UltiCloneName))
                {
                    UltiClone = inGameObject;
                }
            }
        }
Пример #12
0
 public void MoveReport(InGameObject obj)
 {
     movingObject.Add(obj);
     if (currentCycle == GameCycle.InputTime)
     {
         currentCycle = GameCycle.MoveTime;
     }
 }
Пример #13
0
    public override void prepareGameObjectRestore(IList <Transform> nonPrefabs)
    {
        InGameObject = SaveableScene.getTransformFromPath(pathFromRoot).gameObject;
        SaveableNonPrefab saveableNonPrefab = InGameObject.GetComponent <SaveableNonPrefab>();

        saveableNonPrefab.PathFromRoot = pathFromRoot;
        nonPrefabs.Add(InGameObject.transform);
    }
Пример #14
0
                private static void InGameObject_OnDestroy(InGameObject inGameObject)
                {
                    var tryDanger = TrackedObjects.FirstOrDefault(t => t.TravelObject.GameObject == inGameObject);

                    if (tryDanger != default(TrackedCircularJump))
                    {
                        RemoveAfterFrame.Add(tryDanger);
                    }
                }
Пример #15
0
    private InGameObject GetJellyHeroToObjectCrashObject()
    {
        InGameObject crashObject    = null;
        var          jellyHeroAngle = GetCenterToJellyHeroAngle();
        float        minGap         = float.MaxValue;
        int          minGapIndex    = -1;

        for (int i = 0; i < ItemObjectList.Count; i++)
        {
            if (ItemObjectList[i].UniqueIndex >= 0)
            {
                float gap = GetTargetToObjectAngleGap(jellyHeroAngle, ItemObjectList[i]);

                if (minGap > gap)
                {
                    minGap      = gap;
                    minGapIndex = i;
                }
            }
        }



        if (CommonData.IN_GAMEOBJECT_CRASH_DEGREE_GAP >= minGap && minGapIndex >= 0)
        {
            crashObject = ItemObjectList[minGapIndex];
        }

        if (crashObject == null)
        {
            float startCheckGap = GetTargetToObjectAngleGap(jellyHeroAngle, JellyHeroStart);
            if (CommonData.IN_GAMEOBJECT_CRASH_DEGREE_GAP >= startCheckGap)
            {
                crashObject = JellyHeroStart;
            }

            if (PlayJellyHero.JellyMoveRightDir)
            {
                float LeftCheckGap = GetTargetToObjectAngleGap(jellyHeroAngle, JellyHeroEndCheck_Left);
                if (CommonData.IN_GAMEOBJECT_CRASH_DEGREE_GAP >= LeftCheckGap)
                {
                    crashObject = JellyHeroEndCheck_Left;
                }
            }
            else
            {
                float RightCheckGap = GetTargetToObjectAngleGap(jellyHeroAngle, JellyHeroEndCheck_Right);
                if (CommonData.IN_GAMEOBJECT_CRASH_DEGREE_GAP >= RightCheckGap)
                {
                    crashObject = JellyHeroEndCheck_Right;
                }
            }
        }


        return(crashObject);
    }
Пример #16
0
                private static void InGameObject_OnDestroy(InGameObject inGameObject)
                {
                    var tryFind = TrackedObjects.FirstOrDefault(t =>
                                                                t.DashObject.GameObject == inGameObject);

                    if (tryFind != default(TrackedDash))
                    {
                        RemoveAfterFrame.Add(tryFind);
                    }
                }
Пример #17
0
 public void StopReport(InGameObject obj)
 {
     movingObject.Remove(obj);
     //end of move time
     if (movingObject.Count == 0)
     {
         currentCycle = GameCycle.InputTime;
         InputTimeStart();
     }
 }
Пример #18
0
                private static void InGameObject_OnCreate(InGameObject inGameObject)
                {
                    var data = AbilityDatabase.GetObstacle(inGameObject.ObjectName);

                    if (data == null)
                    {
                        return;
                    }
                    AddAfterFrame.Add(new TrackedObstacleObject(inGameObject.Get <MapGameObject>(), data));
                }
Пример #19
0
        private Image RenderObject(GameState state, InGameObject gameObject, IGameObjectRenderer renderer)
        {
            if (renderer == null)
            {
                return(renderersSet.MissedTextureFactory.Invoke(gameObject.ObjectParameters.Size));
            }
            var ticksPerFrame = (int)(InitialTicksPerFrame / Math.Sqrt(Math.Sqrt(state.Speed)));
            var frameNum      = (int)(gameObject.LifetimeTicks % (ulong)(renderer.Frames.Length * ticksPerFrame)) /
                                ticksPerFrame;

            return(renderer.Frames[frameNum]);
        }
Пример #20
0
    public InGameObject createRandomObject(string objectType)
    {
        if (!objectGroups.Contains(objectType) || objects[objectGroups.IndexOf(objectType)].Count == 0)
        {
            return(null);
        }

        int          groupIndex     = objectGroups.IndexOf(objectType);
        InGameObject selectedObject = null;
        int          randomIndex    = Random.Range(0, objects[groupIndex].Count);

        /*
         * this part ensures the minimum instance creation of each object type
         */
        bool minCreated = true;

        foreach (var size in _objectCounts[groupIndex])
        {
            if (size < minObjectCount)
            {
                minCreated = false;
                break;
            }
        }


        if (!minCreated)
        {
            List <int> randomList = new List <int>();
            for (int i = 0; i < _objectCounts[groupIndex].Count; i++)
            {
                if (_objectCounts[groupIndex][i] < minObjectCount)
                {
                    randomList.Add(i);
                }
            }
            randomIndex = randomList[Random.Range(0, randomList.Count)];
        }
        selectedObject = objects[groupIndex][randomIndex];
        _objectCounts[groupIndex][randomIndex]++;
        InGameObject newObject = null;

        if (!selectedObject.isPrefabricated)
        {
            newObject = GameObject.Instantiate(selectedObject);
            newObject.transform.localScale = selectedObject.transform.localScale;
            newObject.transform.SetParent(instanceParent);
            return(newObject);
        }

        newObject = selectedObject.getPrefabObject();
        return(newObject);
    }
Пример #21
0
 public TestOutput GetPrediction(InGameObject target, bool checkCollision, Vector2 fromPos, float overrideRange = 0f)
 {
     if (Speed >= float.Epsilon)
     {
         return(TestPrediction.GetNormalLinePrediction(fromPos, target, overrideRange >= float.Epsilon ? overrideRange : Range, Speed, Radius, checkCollision));
     }
     else
     {
         //I should seriously wrap this into a GetFixedDelayPrediction. So TODO for later.
         return(TestPrediction.GetPrediction(fromPos, target, overrideRange >= float.Epsilon ? overrideRange : Range, 0f, Radius, FixedDelay, 1.75f, checkCollision));
     }
 }
Пример #22
0
    private void AttachOperands()
    {
        List <InGameObject> operands = new List <InGameObject>();

        FindCurrentTrigger();
        for (int i = 1; i < currentTrigger.Count; i++)
        {
            InGameObject operand = gameObjects[(int)currentTrigger[i].x, (int)currentTrigger[i].y, (int)currentTrigger[i].z].GetComponent <InGameObject>();
            operands.Add(operand);
            operand.AddLinkedButton(currentObj.GetComponent <FlipButton>());
        }
        currentObj.GetComponent <FlipButton>().Operands = operands;
    }
Пример #23
0
    // Gets a random object from specified type. Simply dequeue from object type pool;
    public InGameObject GetRandomObjectFromType(string objectType)
    {
        int index = objectGroupNames.IndexOf(objectType);

        if (_pools[index].Count > 0)
        {
            InGameObject returnOBJ = _pools[index].Dequeue();
            returnOBJ.enabled = true;
            return(returnOBJ);
        }
        else
        {
            throw new Exception("Please increase object pool size for" + objectType + " Object type . We run out of objects !!");
        }
    }
Пример #24
0
    /// <summary>
    /// return ingame objects in position
    /// </summary>
    /// <param name="pos"></param>
    /// <returns></returns>
    public List <InGameObject> BlockData(Position pos)
    {
        List <InGameObject> currentBlock = new List <InGameObject>();

        RaycastHit2D[] rayHits = Physics2D.RaycastAll(pos.ToVector3() + Vector3.back, Vector3.forward, 1, 1 << LayerMask.NameToLayer("InGameObject"));
        foreach (RaycastHit2D rayHit in rayHits)
        {
            InGameObject obj = rayHit.transform.GetComponent <InGameObject>();
            if (obj != null)
            {
                currentBlock.Add(obj);
            }
        }
        return(currentBlock);
    }
Пример #25
0
    /// <summary>
    /// generate new map using prefab
    /// </summary>
    public void GenerateMap()
    {
        // currentMapPrefs=Resources.Load<GameObject>("Prefab/Map/Stage"+HandOverData.Stagenum.ToString());
        //currentMap=Instantiate(currentMapPrefs);
        currentMap = StageLoader.instance.LoadLevelUsingPath(HandOverData.StageName);
        //set cam pos

        float minX = 999;
        float maxX = -999;
        float minY = 999;
        float maxY = -999;

        for (int i = 0; i < currentMap.transform.childCount; i++)
        {
            //layer
            Transform layer = currentMap.transform.GetChild(i);
            for (int j = 0; j < layer.childCount; j++)
            {
                InGameObject inGameObj = layer.GetChild(j).GetComponent <InGameObject>();
                if (inGameObj == null)
                {
                    continue;
                }
                Vector2 childPos = inGameObj.CurrentPos.ToVector3();
                if (childPos.x > maxX)
                {
                    maxX = childPos.x;
                }
                if (childPos.x < minX)
                {
                    minX = childPos.x;
                }
                if (childPos.y > maxY)
                {
                    maxY = childPos.y;
                }
                if (childPos.y < minY)
                {
                    minY = childPos.y;
                }
            }
        }
        Vector2 middlePoint = new Vector2((minX + maxX) / 2, (minY + maxY) / 2);

        InGameCamCtrl.instance.SetPosition(middlePoint);
        BackGround.instance.SetPosition(middlePoint);
        ((InGameCamCtrl)InGameCamCtrl.instance).SetThresholdPos(maxX, maxY, minX, minY);
    }
Пример #26
0
        private static void InGameObject_OnDestroy(InGameObject inGameObject)
        {
            if (!_logEnabled)
            {
                return;
            }
            var baseTypes = inGameObject.GetBaseTypes().ToArray();

            if (!baseTypes.Contains("BaseObject"))
            {
                return;
            }
            var baseObj = inGameObject.Get <BaseGameObject>();

            if (_onlyLogLocal && baseObj.Owner != LocalPlayer.Instance)
            {
                return;
            }

            if (inGameObject is Projectile)
            {
                var projectile = (Projectile)inGameObject;
                Console.WriteLine("Name: " + inGameObject.ObjectName);
                Console.WriteLine("Range: " + projectile.Range);
                Console.WriteLine("Speed: " + projectile.StartPosition.Distance(projectile.LastPosition) / projectile.Get <AgeObject>().Age);
                Console.WriteLine("MapColRadius: " + projectile.Radius);
                Console.WriteLine("----");
            }

            if (baseTypes.Contains("TravelBuff"))
            {
                var startPos = inGameObject.Get <TravelBuffObject>().StartPosition;
                Console.WriteLine("Name: " + inGameObject.ObjectName);
                Console.WriteLine("Range: " + LocalPlayer.Instance.Pos().Distance(startPos));
                Console.WriteLine("Duration: " + inGameObject.Get <AgeObject>().Age);
                Console.WriteLine("Speed: " + LocalPlayer.Instance.Pos().Distance(startPos) / inGameObject.Get <AgeObject>().Age);
                Console.WriteLine("----");
            }
            if (baseTypes.Contains("Dash"))
            {
                var startPos = inGameObject.Get <DashObject>().StartPosition;
                Console.WriteLine("Name: " + inGameObject.ObjectName);
                Console.WriteLine("Range: " + LocalPlayer.Instance.Pos().Distance(startPos));
                Console.WriteLine("Duration: " + inGameObject.Get <AgeObject>().Age);
                Console.WriteLine("Speed: " + LocalPlayer.Instance.Pos().Distance(startPos) / inGameObject.Get <AgeObject>().Age);
                Console.WriteLine("----");
            }
        }
Пример #27
0
    /// <summary>
    /// resize laser's length
    /// </summary>
    public void Resize()
    {
        Position tempEndPos = null;

        if (currentPos == null)
        {
            Start();
        }
        RaycastHit2D[] hits = Physics2D.RaycastAll(currentPos.ToVector3(), Direction.Dir4ToPos(dir).ToVector3(), maxLength, 1 << LayerMask.NameToLayer("InGameObject"));
        for (int i = 0; i < hits.Length; i++)
        {
            InGameObject temp = hits[i].transform.GetComponent <InGameObject>();
            if (temp.GetType().IsSubclassOf(typeof(LoadedObject)) &&
                temp.CurrentPos != currentPos)
            {
                if (temp.GetType().IsSubclassOf(typeof(DestroyableObject)))
                {
                    if (!((DestroyableObject)temp).IsDestroyed)
                    {
                        ((DestroyableObject)temp).Destroy();
                        return;
                    }
                }
                tempEndPos = temp.CurrentPos;
                break;
            }
        }

        if (tempEndPos == null)
        {
            tempEndPos = currentPos + Direction.Dir4ToPos(dir) * maxLength;
        }

        endPos = tempEndPos;
        Position laserPos = tempEndPos - currentPos;

        if (Mathf.Abs(laserPos.X) > Mathf.Abs(laserPos.Y))
        {
            laserLength = laserPos.X;
        }
        else
        {
            laserLength = laserPos.Y;
        }
        SetSortingOrder();
        SetLaserShape();
    }
Пример #28
0
        private static bool EnemyProjectileGoingToHitUnit(InGameObject unit, out Projectile closestProj)
        {
            var unitPos    = unit.Get <MapGameObject>().Position;
            var unitRadius = unit.Get <SpellCollisionObject>().SpellCollisionRadius;
            var enemyProjs = EntitiesManager.ActiveProjectiles.Where(x => x.BaseObject.TeamId != KaanHero.BaseObject.TeamId).OrderBy(x => x.MapObject.Position.Distance(unitPos));

            foreach (var enemyProj in enemyProjs)
            {
                if (Geometry.CircleVsThickLine(unitPos, unitRadius, enemyProj.StartPosition, enemyProj.CalculatedEndPosition, enemyProj.Radius, false))
                {
                    closestProj = enemyProj;
                    return(true);
                }
            }

            closestProj = null;
            return(false);
        }
Пример #29
0
 private static void InGameObject_OnCreate(InGameObject inGameObject)
 {
     if (inGameObject.GetBaseTypes().Contains("Throw"))
     {
         var throwObj = inGameObject.Get <ThrowObject>();
         var data     = throwObj.Data();
         if (data == null)
         {
             return;
         }
         if (LocalPlayer.Instance.Pos().Distance(throwObj.TargetPosition) > 5)
         {
             return;
         }
         var tto = new TrackedThrowObject(throwObj, data);
         AddAfterFrame.Add(tto);
     }
 }
Пример #30
0
 private static void InGameObject_OnCreate(InGameObject inGameObject)
 {
     if (inGameObject.GetBaseTypes().Contains("TravelBuff"))
     {
         var travelObj = inGameObject.Get <TravelBuffObject>();
         var data      = travelObj.Data();
         if (data == null || data.AbilityType != AbilityType.CircleJump)
         {
             return;
         }
         if (LocalPlayer.Instance.Pos().Distance(travelObj.TargetPosition) > 5)
         {
             return;
         }
         var tcj = new TrackedCircularJump(travelObj, data);
         AddAfterFrame.Add(tcj);
     }
 }
Пример #31
0
		protected override void LoadContent()
		{
				//grab a handle on the content manager
				ContentManager content = (ContentManager)this.Game.Services.GetService(typeof(ContentManager));

				_effect = this.GetService<ContentManager>().Load<Effect>(@"Terrain\SimpleTerrain");
				/*foreach (EffectTechnique technique in _effect.Techniques.GetValidTechniques())
				{
					_effect.CurrentTechnique = technique;
					break;
				}*/

				// if we have a height map, use this for the dimensions
				if (_heightMapName != null)
				{
					//read the height data from the height map
					Texture2D _heightmapTexture = content.Load<Texture2D>(_heightMapName);
					//take the size from the height map (we're assuming it is square)
					_size = _heightmapTexture.Width;

					//translationMatrix = Matrix.CreateTranslation(-_size / 2, 0, -_size / 2);
					//translationMatrix = Matrix.CreateTranslation(0, 0, 0);

					//get the heights from the height map
					Color[] heights = new Color[_size * _size];
					_heightmapTexture.GetData<Color>(heights);

					_heightMap = new float[_size * _size];
					//take the red values for height data
					for (int i = 0; i < _size * _size; i++)
					{
						_heightMap[i] = heights[i].R;
					}
				}

				_numVertices = _size * _size;
				int numInternalRows = _size - 2;
				_numIndices = (2 * _size * (1 + numInternalRows)) + (2 * numInternalRows);

				//our map is square
				const int MAPDIMENSION = 2048;
				_mapScale = new Vector3(MAPDIMENSION / (float)_size, 1.0f, MAPDIMENSION / (float)_size);
				_mapOffset = new Vector3(-MAPDIMENSION / 2, 1, -MAPDIMENSION / 2);	//move to origin

				//get our map objects
				Texture2D objectMapTexture = content.Load<Texture2D>(_objectMapName);
				int objectMapSize = objectMapTexture.Width;
				Color[] objects = new Color[objectMapSize * objectMapSize];
				objectMapTexture.GetData<Color>(objects);
				Vector3 mapObjectScale = new Vector3(MAPDIMENSION / (float)objectMapSize, 1.0f, MAPDIMENSION / (float)objectMapSize);

				//list which model to use for each object
				InGameObject[] inGameObject = new InGameObject[256];
				inGameObject[255] = new InGameObject("Cone", 1.5f, false, false, 50);
				inGameObject[254] = new InGameObject("Building1", 4.0f, true, false, 5);
				inGameObject[253] = new InGameObject("Building2", 4.0f, true, false, 5);
				inGameObject[252] = new InGameObject("Building3", 4.0f, true, false, 5);
				inGameObject[251] = new InGameObject("Building4", 5.0f, true, false, 5);
				inGameObject[250] = new InGameObject("Building5", 8.0f, true, false, 5);
				inGameObject[249] = new InGameObject("Building6", 4.0f, true, false, 5);
				inGameObject[248] = new InGameObject("Building7", 4.0f, true, false, 5);
				inGameObject[247] = new InGameObject("Building8", 4.0f, true, false, 5);
				inGameObject[246] = new InGameObject("Checkpoint", 1.0f, false, false, 5);
				inGameObject[245] = new InGameObject("bridge", 7.0f, true, false, 5);

				inGameObject[243] = new InGameObject("sheep", 3.0f, false, false, 25);

				//take the red values for height data
				for (int i = 0; i < objectMapSize * objectMapSize; i++)
				{
					//extract object info from colours
					int objectIndex = objects[i].R;
					float objectRotation = (float)objects[i].G / 256.0f * 360.0f;
					if (inGameObject[objectIndex] != null)
					{
						if (inGameObject[objectIndex].createdInstances < inGameObject[objectIndex].maxInstances)
						{
							Vector3 newObjectPos = new Vector3(i % objectMapSize - 10, 0.0f, (int)(i / objectMapSize) - 10) * mapObjectScale + _mapOffset;
							newObjectPos.Y = GetHeight(newObjectPos.X, newObjectPos.Z);
							Matrix trans = Matrix.CreateRotationY(MathHelper.ToRadians(objectRotation)) * Matrix.CreateScale(inGameObject[objectIndex].scale) * Matrix.CreateTranslation(newObjectPos);

							GameObject newObject;
							newObject = CreateMesh(this.Game, inGameObject[objectIndex].model, trans);

							newObject.collidable = inGameObject[objectIndex].collideable;
							newObject.moveable = inGameObject[objectIndex].moveable;

							if (objectIndex == 255)
							{
								// cone
								Physics.ParticleSystem newCone = new Physics.ParticleSystem(this.Game, global::AwesomeGame.Physics.enumPhysicsObjects.Cone, newObjectPos);
								newCone.graphicObject = newObject;	//tell it to use the new graphics object for display
								this.Game.Components.Add(newCone);	//the physics need to be added to the components
							}
							if (objectIndex == 243)
							{
								// sheep
								Physics.ParticleSystem newSheep = new Physics.ParticleSystem(this.Game, global::AwesomeGame.Physics.enumPhysicsObjects.Sheep, newObjectPos);
								newSheep.graphicObject = newObject;	//tell it to use the new graphics object for display
								this.Game.Components.Add(newSheep);	//the physics need to be added to the components
							}
							if (objectIndex == 246)
							{
								//add a checkpoint to the course
								((Course)this.Game.Services.GetService(typeof(Course))).addCheckpoint(newObject);
							}

							//add the objects to the game components
							this.Game.Components.Add(newObject);

							//increment the count of this number of objects
							inGameObject[objectIndex].createdInstances++;
						}
					}
				}

				//generate texture vertices
				NormalMap normalMap = new NormalMap(this);
				Color[] normals = new Color[_size * _size];
				VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[_numVertices];
				for (int z = 0; z < _size; z++)
				{
					for (int x = 0; x < _size; x++)
					{
						Vector3 normal = normalMap.GetNormal(x, z);
						vertices[GetIndex(x, z)] = new VertexPositionNormalTexture(
							GetPosition(x, z),
							normal,
							new Vector2(x / (float) (_size - 1), z / (float) (_size - 1)));
							//new Vector2(2.0f * x / _size , 2.0f * z / _size ));

						normal /= 2;
						normal += new Vector3(0.5f);
						normals[GetIndex(x, z)] = new Color(normal);
					}
				}

				_vertexBuffer = new VertexBuffer(
					this.GraphicsDevice,
					VertexPositionNormalTexture.VertexDeclaration,
					vertices.Length,
					BufferUsage.WriteOnly);
				_vertexBuffer.SetData<VertexPositionNormalTexture>(vertices);

				short[] indices = new short[_numIndices]; int indexCounter = 0;

				for (int z = 0; z < _size - 1; z++)
				{
					// insert index for degenerate triangle
					if (z > 0)
						indices[indexCounter++] = GetIndex(0, z);

					for (int x = 0; x < _size; x++)
					{
						indices[indexCounter++] = GetIndex(x, z);
						indices[indexCounter++] = GetIndex(x, z + 1);
					}

					// insert index for degenerate triangle
					if (z < _size - 2)
						indices[indexCounter++] = GetIndex(_size - 1, z);
				}

				_indexBuffer = new IndexBuffer(
					this.GraphicsDevice,
					IndexElementSize.SixteenBits,
					indices.Length,
					BufferUsage.WriteOnly);
				_indexBuffer.SetData(indices);

				if (_textureAssetName != null)
				{
					_texture = content.Load<Texture2D>(_textureAssetName);
				}

				_effect.Parameters["GrassTexture"].SetValue(_texture);
				_effect.Parameters["TerrainSize"].SetValue(_size);

				_normalMap = new Texture2D(this.GraphicsDevice, _size, _size, true, SurfaceFormat.Color);
				_normalMap.SetData<Color>(normals);
				_effect.Parameters["NormalMapTexture"].SetValue(_normalMap);

				ShadowMap shadowMap = GetService<ShadowMap>();
				if (shadowMap != null)
				{
					_effect.Parameters["ShadowMapSize"].SetValue(shadowMap.ShadowMapSize);
					_effect.Parameters["ShadowMapSizeInverse"].SetValue(1.0f / (float) shadowMap.ShadowMapSize);

					float offset = 0.5f + (0.5f / (float) shadowMap.ShadowMapSize);
					_textureScaleAndOffsetMatrix = new Matrix(
						0.5f, 0.0f, 0.0f, 0.0f,
						0.0f, -0.5f, 0.0f, 0.0f,
						0.0f, 0.0f, 1.0f, 0.0f,
						offset, offset, 0.0f, 1.0f);
				}
		}