用于产生随机数据的类。
コード例 #1
0
ファイル: ItemRebounce.cs プロジェクト: Midimistro/Deadmen
    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    //override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
    //
    //}

    // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if(animator.GetBool("Grounded"))
        {
            UnityEngine.Random rnd = new UnityEngine.Random();
            //animator.GetComponentInParent<Rigidbody>().AddForce(new Vector3(rnd.RandomRange(-1.0f, 1.0f), rnd.RandomRange(-20.0f, 20.0f), rnd.RandomRange(-1.0f, 1.0f));
            animator.GetComponentInParent<Rigidbody>().AddForce(new Vector3(0f, 20f, 0f));
            animator.SetBool("Grounded", false);
        }
    }
コード例 #2
0
	static public int constructor(IntPtr l) {
		try {
			UnityEngine.Random o;
			o=new UnityEngine.Random();
			pushValue(l,true);
			pushValue(l,o);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
コード例 #3
0
 public static int constructor(IntPtr l)
 {
     try {
         UnityEngine.Random o;
         o=new UnityEngine.Random();
         pushValue(l,o);
         return 1;
     }
     catch(Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return 0;
     }
 }
コード例 #4
0
    public Order()
    {
        this.FormColor = (FormColor)Random.Range(0, Enum.GetValues(typeof(FormColor)).Length);

        var allAttachments = Enum.GetValues(typeof(Attachment)) as Attachment[];
        var availableAtt   = allAttachments.ToList();

        var attachmentCount     = Random.Range(0, Enum.GetValues(typeof(Attachment)).Length + 1);
        var requiredAttachments = new List <Attachment>();

        while (attachmentCount > 0)
        {
            var attch = availableAtt.PickOne();
            requiredAttachments.Add(attch);
            availableAtt.Remove(attch);
            attachmentCount--;
        }

        Attachments = requiredAttachments.ToArray();
        TimeLimit   = baseTime + (timeFactor * Attachments.Length);
    }
コード例 #5
0
	static int _CreateUnityEngine_Random(IntPtr L)
	{
		try
		{
			int count = LuaDLL.lua_gettop(L);

			if (count == 0)
			{
				var obj = new UnityEngine.Random();
				ToLua.PushSealed(L, obj);
				return 1;
			}
			else
			{
				return LuaDLL.luaL_throw(L, "invalid arguments to ctor method: UnityEngine.Random.New");
			}
		}
		catch (Exception e)
		{
			return LuaDLL.toluaL_exception(L, e);
		}
	}
コード例 #6
0
    public static bool GetPercentageBasedBoolean(int percent)
    {
        Dictionary <int, bool> values = new Dictionary <int, bool> ();
        int remainTrueValues          = percent;

        for (int i = 0; i < MaxPercent; i++)
        {
            if (remainTrueValues > 0)
            {
                values.Add(i, true);
                remainTrueValues--;
            }
            else
            {
                values.Add(i, false);
            }
        }
        init();
        int randIndex = Random.Range(0, MaxPercent);

        return(values [randIndex]);
    }
コード例 #7
0
    public Grid <TileType> Generate(int sizeX, int sizeY)
    {
        m_grid.SetSize(sizeX, sizeY, TileType.Empty);

        // divide the map into four quadrants for four rooms, once on x and once on y
        var divX = Random.Range((sizeX / 2) - 2, (sizeX / 2) + 3);
        var divY = Random.Range((sizeY / 2) - 2, (sizeY / 2) + 3);

        // create four rooms
        var bottomLeft  = CreateRandomRoom(0, divX - 1, 0, divY - 1);
        var bottomRight = CreateRandomRoom(divX + 1, sizeX - 1, 0, divY - 1);
        var upperLeft   = CreateRandomRoom(0, divX - 1, divY + 1, sizeY - 1);
        var upperRight  = CreateRandomRoom(divX + 1, sizeX - 1, divY + 1, sizeY - 1);

        // create four corridors between the rooms
        CreateRandomCorridor(bottomLeft, upperLeft);
        CreateRandomCorridor(bottomRight, upperRight);
        CreateRandomCorridor(bottomLeft, bottomRight);
        CreateRandomCorridor(upperLeft, upperRight);

        return(m_grid);
    }
コード例 #8
0
    protected override void OnUpdate()
    {
        // add random component
        if (query.CalculateEntityCount() != 0)
        {
            var native = query.ToEntityArray(Allocator.Temp);
            for (int i = 0; i < native.Length; i++)
            {
                var entity = native[i];
                EntityManager.AddComponentData(entity, new RandomDirection {
                    Direction = new float3(Random.Range(-1, 1f), Random.Range(-1, 1f), Random.Range(-1, 1f))
                });
            }

            native.Dispose();
        }
        float time = Time.DeltaTime;

        Entities.ForEach((Entity entity, ref Translation translation, in RandomDirection randomDirection) =>
        {
            //translation.Value += time * randomDirection.Direction * 2;
        }).Schedule();
    }
コード例 #9
0
    public static int[] RandomIndex(int InMin, int InMax, int InCount)
    {
        int length = InMax - InMin;

        Assert.IsTrue(length >= InCount);

        int[] array = new int[length];
        for (int i = 0; i < length; i++)
        {
            array[i] = InMin + i;
        }

        int[] result = new int[InCount];
        for (int i = 0; i < InCount; i++)
        {
            int index = Random.Range(0, length);
            result[i]    = array[index];
            array[index] = array[length - 1];
            --length;
        }

        return(SortUtility.BubbleSort(result));
    }
コード例 #10
0
    private static string Stutter(Match m)
    {
        string x       = m.ToString();
        string stutter = "";

        //20% chance to stutter at any given consonant
        if (Random.Range(1, 6) == 1)
        {
            //Randomly pick how bad is the stutter
            int intensity = Random.Range(1, 4);
            for (int i = 0; i < intensity; i++)
            {
                stutter = stutter + x + "... "; //h... h... h...
            }

            stutter = stutter + x; //h... h... h... h[ello]
        }
        else
        {
            stutter = x;
        }
        return(stutter);
    }
コード例 #11
0
    /// <summary>
    /// Randomly choose points within a range (defined by `xMin`, `xMax`, `yMin`, `yMax`) until the point is
    /// underneath the curve defined by function `fn`. This is a simple and expensive way of sampling
    /// any weighted random function.
    /// However, over time, the expected amount of loops in this call will amortise to:
    ///     region_area / fn_area
    ///
    /// Where `region_area` represents the area of the region (i.e. `(xMax-xMin) * (yMax-yMin)`) and
    /// `fn_area` represents the total area underneath the function `fn`. In all real world scenarios
    /// this will likely never be more than, say, 10 or so.
    /// </summary>
    /// <param name="fn">Function defining the weight for random sampling</param>
    /// <param name="xMin">Minimum x value of the region to sample from</param>
    /// <param name="xMax">Maximum x value of the region to sample from</param>
    /// <param name="yMin">Minimum y value of the region to sample from</param>
    /// <param name="yMax">Maximum y value of the region to sample from</param>
    /// <returns>A random number between `xMin` (inclusive) and `xMax` (exclusive), weighted by `fn`</returns>
    private static float SampleRegion(Func <float, float> fn, float xMin, float xMax, float yMin, float yMax)
    {
        int   i = 0;
        float x, y = 1, result = 0;

        do
        {
            x = Random.Range(xMin, xMax);

            // Ensure we never return `xMax` as our result
            //  as we promised that `xMax` was exclusive
            if (x == xMax)
            {
                continue;
            }

            y      = Random.Range(yMin, yMax);
            result = fn(x);
            i++;
        } while (y > result);

        return(x);
    }
コード例 #12
0
    private void PickAreas()
    {
        _areas = new Dictionary <Area, SettlementSection>();
        for (var i = 0; i < _numAreasForSettlementSize[Size]; i++)
        {
            var settlementPlaced = false;
            while (!settlementPlaced)
            {
                var x = Random.Range(0, _cell.GetCellHeight());
                var y = Random.Range(0, _cell.GetCellWidth());

                if (_areas.Count > 0 && !AreaIsAdjacentToAnotherSettlementArea(x, y))
                {
                    continue;
                }

                var area = _cell.Areas[x, y];

                if (_areas.ContainsKey(area))
                {
                    continue;
                }

                area.Settlement        = this;
                area.SettlementSection = new SettlementSection();

                if (area.PresentFactions == null)
                {
                    area.PresentFactions = new List <Faction>();
                }

                area.PresentFactions.Add(Faction);
                _areas.Add(area, area.SettlementSection);
                settlementPlaced = true;
            }
        }
    }
コード例 #13
0
ファイル: EnemyBoss.cs プロジェクト: heze8/OnlyOne
    private void FirstShootingState(Vector3 enemyShootDirection)
    {
        if (canShoot && !isPaused && WithinRange(enemyShootDirection, shootDistance))
        {
            RaycastHit2D hit = Physics2D.Linecast(transform.position, target.position, layerMask);
            if (hit.collider != null)
            {
                canShoot = false;
                //after finding a wall, jump, pause and find another path
                Jump();
                StartCoroutine(ReShoot(2f));
                return;
            }

            canShoot = false;
            Shoot();
            StartCoroutine(ReShoot(shootDelay));
            if (shotsFired > Random.Range(2, 7))
            {
                shotsFired = 0;
                StartCoroutine(PauseShooting(pauseDuration));
            }
        }
    }
コード例 #14
0
    static void Dup()
    {
        Undo.RegisterSceneUndo("rtools");
        var n = "D" + Random.Range(10, 99) + ".mat";

        foreach (var m in Selection.gameObjects.Select(a => a.renderer).SelectMany(a => a.sharedMaterials))
        {
            var p   = AssetDatabase.GetAssetPath(m);
            var nwp = p.Substring(0, p.Length - 4) + n;
            AssetDatabase.CopyAsset(p, nwp);
            AssetDatabase.Refresh();
        }
        foreach (var a in Selection.gameObjects.Select(a => a.renderer))
        {
            var ms = a.sharedMaterials;
            for (int i = 0; i < ms.Count(); i++)
            {
                var p   = AssetDatabase.GetAssetPath(ms[i]);
                var nwp = p.Substring(0, p.Length - 4) + n;
                ms[i] = (Material)AssetDatabase.LoadAssetAtPath(nwp, typeof(Material));
            }
            a.sharedMaterials = ms;
        }
    }
コード例 #15
0
    public static BlockArray CreateTestArray()
    {
        var blockArray = new BlockArray();

        blockArray.Values = new BlockStruct[100 * 100];
        var index = 0;

        for (var x = 0; x < 100; x++)
        {
            for (var y = 0; y < 100; y++)
            {
                var blockStruct = new BlockStruct
                {
                    Type     = (short)Random.Range(0, 5),
                    GroupId  = 0,
                    Position = new int2(x, y),
                    FrameCountLastUpdated = 0,
                };
                blockArray.Values[index++] = blockStruct;
            }
        }

        return(blockArray);
    }
コード例 #16
0
    private IEnumerator SpotArrivalCheck(Character character)
    {
        yield return(new WaitForSeconds(Random.Range(0.5f, 3f)));

        if (InArea == null)
        {
            Debug.LogError(name + " not in Area");
            yield break;
        }

        //if enemy and not fleeing or fighting and attentive enough
        //TODO: double up chance as scout
        if (!InArea.AnyEnemies() && this as Goblin & !Fleeing() & !Hiding() && Alive() & !Attacking() && character.tag == "Enemy")
        {
            if (Random.Range(0, 12) < SMA.GetStatMax())
            {
                (this as Goblin).Shout("I see enemy!!", SoundBank.GoblinSound.EnemyComing);
            }
            //else
            //{
            //    Debug.Log(name + " failed enemy spoting");
            //}
        }
    }
コード例 #17
0
 private void InitWep()
 {
     if (this.weapons.Length > 0)
     {
         RightHand = FirstOrDefault(transforms, a => a.tag == "rhand");
         weapon    = this.weapons[Random.Range(0, this.weapons.Length)];
         if (RightHand != null)
         {
             var original = weapon.weaponPrefab;
             weaponObj = (GameObject)Instantiate(original, RightHand.position + original.transform.position, RightHand.rotation * original.transform.rotation);
             if (weaponObj.collider == null)
             {
                 weaponObj.AddComponent <BoxCollider>();
                 weaponObj.collider.enabled = false;
                 m_colliders = null;
             }
             weaponObj.transform.parent = RightHand;
         }
     }
     if (weapon == null)
     {
         weapon = _Database.defWep;
     }
 }
コード例 #18
0
    //boss出招技能
    private void BossSkillSelect()
    {
        int temp;
        while (true)
        {
            int rdNum = Random.Range(1,101);
            if (rdNum<=40)
            {
                temp = 1;
            }
            else if (rdNum<=60)
            {
                temp = 2;
            }
            else if (rdNum<=80)
            {
                temp = 3;
            }
            else if (rdNum<=90)
            {
                temp = 4;
            }
            else
            {
                temp = 0;
            }
            if (lastSkill!=temp)
            {
                lastSkill = temp;
                break;
            }
        }
        int skillID = bossSkillArray[temp];

        currentBossSkill = skillID;
    }
コード例 #19
0
ファイル: ProgressBar.cs プロジェクト: talentone/unitystation
    /// <summary>
    /// Logic for starting a progress bar used on both client and server.
    /// </summary>
    private void CommonStartProgress()
    {
        //always upright in world space
        transform.rotation = Quaternion.identity;
        done = false;
        //common logic used between client / server progress start logic
        matrixMove = GetComponentInParent <MatrixMove>();
        if (matrixMove != null)
        {
            matrixMove.MatrixMoveEvents.OnRotate.AddListener(OnRotationEnd);
        }

        anim = 0f;
        if (Random.value < 0.02f)
        {
            spriteRenderer.transform.parent.localRotation = Quaternion.identity;
            animIdx = Random.Range(1, progressSprites.Length / 2);
            animSpd = Random.Range(360f, 720f);
        }
        else
        {
            animIdx = -1;
        }
    }
コード例 #20
0
        private IEnumerator CreateEnemies(int level, Action nextLevel)
        {
            var sleepTime = _amountTimeToInvoke / _amountEnemies;
            var bound     = Camera.main.OrthographicBounds();

            for (var i = 0; i < _amountEnemies; i++)
            {
                var enemy = Game.EnemiesPool.GetItem().GetComponent <SpaceShipEnemies>();
                var gun   = enemy.GetComponent <SphericalGunSystem>();
                gun.AmountDirection = (int)Random.Range(_nbDirectionShooting.x, _nbDirectionShooting.y);

                enemy.Speed = Random.Range(0.8f, 2.3f);
                enemy.Life  = Mathf.CeilToInt(Mathf.Pow(level, 1.8f)) + 2;
                enemy.transform.position = new Vector2(
                    bound.center.x + Random.Range(-bound.extents.x + OffsetOffScreen, bound.extents.x - OffsetOffScreen),
                    bound.center.y + bound.extents.y + OffsetOffScreen + Random.Range(0, RandomnessOffScreen)
                    );

                _enemies.Add(enemy);

                if (i + 1 < _amountEnemies)
                {
                    yield return(new WaitForSeconds(sleepTime));
                }
            }

            while (!_enemies.TrueForAll(e => !e.IsAlive))
            {
                yield return(null);
            }

            _enemies.ForEach(e => e.TrowAway());
            _enemies.Clear();

            nextLevel();
        }
コード例 #21
0
ファイル: PostAllignment.cs プロジェクト: eusekerci/LDJam42
    private void InitializePosts()
    {
        _posts          = new List <Post>();
        _postTransforms = new List <Transform>();

        for (int i = 0; i < _currentPlayerCount; i++)
        {
            _postTransforms.Add(Instantiate(_postPrefab, _postRoot).transform);
            _postTransforms[i].name = "Post" + (i + 1).ToString();
            _playerManager.GetPlayer(i).SetPost(_postTransforms[i]);
            _posts.Add(_postTransforms[i].GetComponent <Post>());
        }

        var direction = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;

        for (int i = 0; i < _currentPlayerCount; i++)
        {
            _postTransforms[i].position = direction * _circleRange;
            direction = Utils.Vector2Extension.Rotate(direction,
                                                      _playerManager.GetPlayer(i).GetScore() * Mathf.Rad2Deg);

            _posts[i].Init(_playerManager.GetPlayer(i));
        }
    }
コード例 #22
0
    protected void SpawnSmoke()
    {
        if (!Smoke)
        {
            return;
        }
        var lifeTime = Random.Range(3, 3);

        // Pos
        var pos = FXSocket.position;

        pos.z = 0;

        // Rotation
        var rot       = FXSocket.rotation;
        var smoke     = F3DSpawner.Spawn(Smoke, pos, rot, null);
        var direction = Mathf.Sign(FXSocket.parent.lossyScale.x);
        var dirScale  = smoke.localScale;

        dirScale.x      *= direction;
        smoke.localScale = dirScale;
        _smokeEffects.Add(smoke);
        F3DSpawner.Despawn(smoke, lifeTime);
    }
コード例 #23
0
        private IEnumerator SpawnRabbits()
        {
            // generating colors for each rabbit
            Color[] palette = new Color[nbRabbit];
            VisionUtility.GetColorBlindSafePalette(palette, 0.5f, 1.0f);

            for (uint i = 0; i < nbRabbit; i++)
            {
                // instantiating rabbit in circle
                var randomCircle = Random.insideUnitCircle;

                var rabbit = Instantiate(
                    rabbitPrefab,
                    spawnCenter.TransformPoint(new Vector3(randomCircle.x, 0, randomCircle.y) * spawnRange),
                    Quaternion.Euler(0, Random.Range(0, 360), 0)
                    );

                // setting scale of rabbit
                rabbit.transform.localScale = Vector3.one * Random.Range(0.8f, 1.4f);

                // setting color of rabbit
                foreach (var rabbitRenderer in rabbit.GetComponentsInChildren <Renderer>())
                {
                    if (rabbitRenderer.material.color == Color.black ||
                        rabbitRenderer.material.color == Color.white)
                    {
                        continue;
                    }

                    rabbitRenderer.material.color = palette[i];
                }

                // waiting before next rabbit
                yield return(new WaitForSeconds(Random.Range(0.5f, 3f)));
            }
        }
コード例 #24
0
        public void SetupBoard(int seed, bool forPlanner, BoardManager.Count wallCount, BoardManager.Count leverCount, int enemyCount)
        {
            Random.InitState(seed);
            //Creates the outer walls and floor.
            CleanBoard();


            //Instantiate a random number of wall tiles based on minimum and maximum, at randomized positions.
            LayoutWallAtRandom(wallCount.minimum, wallCount.maximum);

            if (forPlanner)
            {
                //Instantiate a random number of food tiles based on minimum and maximum, at randomized positions.
                LayoutItemsAtRandom(leverCount.minimum, leverCount.maximum);
            }



            LayoutGoalAtRandom(forPlanner);
            if (enemyCount > 0)
            {
                LayoutEnemiesAtRandom(enemyCount);
            }
        }
コード例 #25
0
    //add tile
    private void AddTile(Vector2 position, bool hasWall)
    {
        // if board has this tile, do nothing
        if (positionGrid.ContainsKey(position))
        {
            return;
        }

        //add normal word tile
        positionGrid.Add(position, position);
        GameObject tile         = floorTiles[Random.Range(0, floorTiles.Length)];
        GameObject tileInstance = Instantiate(tile, new Vector3(position.x, position.y, 0f), Quaternion.identity, gameBoardHolder) as GameObject;

        //add tile of dungeon's entrance
        if (Random.Range(0, 100) == 1)
        {
            tile         = exit;
            tileInstance = Instantiate(tile, new Vector3(position.x, position.y, 0f), Quaternion.identity, gameBoardHolder) as GameObject;
        }

        //add walls tile
        else if (Random.Range(0, 5) == 1)
        {
            //add 0.2 possibility to generate a wall on tile
            if (hasWall)
            {
                tile         = wallTiles[Random.Range(0, wallTiles.Length)];
                tileInstance = Instantiate(tile, new Vector3(position.x, position.y, 0f), Quaternion.identity, gameBoardHolder) as GameObject;
            }
        }
        else if (Random.Range(0, GameManager.instance.enemyRatio) == 1)
        {
            tile         = enemy;
            tileInstance = Instantiate(tile, new Vector3(position.x, position.y, 0f), Quaternion.identity, gameBoardHolder) as GameObject;
        }
    }
コード例 #26
0
ファイル: BoardManager.cs プロジェクト: zaflores/GMTKJam
    private void CreateGameBoard(float offsetX, float offsetY)
    {
        for (int i = 0; i < _xTitles; i++)
        {
            for (int j = 0; j < _yTitles; j++)
            {
                Vector2    positionToSpawn = new Vector2(_startPosForGameBoard.x + offsetX * i, _startPosForGameBoard.y + offsetY * j);
                GameObject title           = Instantiate(_titleNormalPrefab, positionToSpawn, Quaternion.identity);
                gameBoard[i, j]        = title;
                title.transform.parent = transform;
                int spriteToChoose = Random.Range(0, _gameSprites.Length);
                while (numOfEachSprite[spriteToChoose] == 0)
                {
                    spriteToChoose = Random.Range(0, numOfEachSprite.Length);
                }

                title.GetComponent <SpriteRenderer>().sprite = _gameSprites[spriteToChoose];
                Tile temptile = title.GetComponent <Tile>();
                temptile.SetCoordinate(i, j);
                temptile.SetType(spriteToChoose);
                numOfEachSprite[spriteToChoose]--;
            }
        }
    }
コード例 #27
0
    // Use this for initialization
    void Start()
    {
        //Villager.Create();

        Terrain.Instance.Regenerate();

        for (int i = 0; i < 2; i++)
        {
            Vector2Int villagePos;
            do
            {
                villagePos = new Vector2Int(Random.Range(0, LENGTH), Random.Range(0, WIDTH));
            } while (Terrain.Instance.GetTerrainType(villagePos) == global::Terrain.TerrainType.Land);

            _villages.Add(Village.Create(villagePos));
        }

        // Spawn trees
        for (int x = 0; x < LENGTH; x++)
        {
            for (int y = 0; y < WIDTH; y++)
            {
                if (Terrain.Instance.GetTerrainType(new Vector2Int(y, x)) == Terrain.TerrainType.Land && Random.Range(0.0f, 100f) > 99.7f)
                {
                    Tree.Create(new Vector2Int(x, y));
                }
            }
        }

        StartCoroutine("SpawnFood");

        for (int i = 0; i < 20; i++)
        {
            SpawnFood();
        }
    }
コード例 #28
0
    protected void SpawnBarrelSpark()
    {
        if (!BarrelSpark)
        {
            return;
        }
        var lifeTime = Random.Range(3, 3);

        // Pos
        var pos = FXSocket.position;

        pos.z = 0;

        // Rotation
        var rot         = FXSocket.rotation;
        var barrelSpark = F3DSpawner.Spawn(BarrelSpark, pos, rot, null);

        _dir = Mathf.Sign(FXSocket.parent.lossyScale.x);
        var dirScale = barrelSpark.localScale;

        dirScale.x            *= _dir;
        barrelSpark.localScale = dirScale;
        F3DSpawner.Despawn(barrelSpark, lifeTime);
    }
コード例 #29
0
        // Called by the camera to apply the image effect
        void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            SanitizeParameters();

            if (scratchTimeLeft <= 0.0f)
            {
                scratchTimeLeft = Random.value * 2 / scratchFPS; // we have sanitized it earlier, won't be zero
                scratchX        = Random.value;
                scratchY        = Random.value;
            }
            scratchTimeLeft -= Time.deltaTime;

            Material mat = material;

            mat.SetTexture("_GrainTex", grainTexture);
            mat.SetTexture("_ScratchTex", scratchTexture);
            float grainScale = 1.0f / grainSize; // we have sanitized it earlier, won't be zero

            mat.SetVector("_GrainOffsetScale", new Vector4(
                              Random.value,
                              Random.value,
                              (float)Screen.width / (float)grainTexture.width * grainScale,
                              (float)Screen.height / (float)grainTexture.height * grainScale
                              ));
            mat.SetVector("_ScratchOffsetScale", new Vector4(
                              scratchX + Random.value * scratchJitter,
                              scratchY + Random.value * scratchJitter,
                              (float)Screen.width / (float)scratchTexture.width,
                              (float)Screen.height / (float)scratchTexture.height
                              ));
            mat.SetVector("_Intensity", new Vector4(
                              Random.Range(grainIntensityMin, grainIntensityMax),
                              Random.Range(scratchIntensityMin, scratchIntensityMax),
                              0, 0));
            Graphics.Blit(source, destination, mat);
        }
コード例 #30
0
        /// <summary>
        /// Instantiate and return all the prefabs that should be spawned at or around the supplied position.
        /// </summary>
        public GameObject[] InstantiatePrefabs(Vector3 position, string namePostfix)
        {
            List <GameObject> spawned = new List <GameObject>();

            Quaternion rotation = Quaternion.Euler(new Vector3(0, Random.Range(0, 359.9f), 0));

            GameObject go;
            string     name = "";

            for (int prefabIdx = 0; prefabIdx < m_SpawnObjectDefinitions.Length; prefabIdx++)
            {
                SpawnObjectDefinition spawnedPrefab = m_SpawnObjectDefinitions[prefabIdx];

                if (spawnedPrefab.probability >= Random.value)
                {
                    if (string.IsNullOrEmpty(name))
                    {
                        name = spawnedPrefab.prefab.name;
                    }

                    // We do this juggling with names because the Brain gets initialized in the Awake and thus it has the wrong name if we add the postfix after creation
                    spawnedPrefab.prefab.name = name + " - " + namePostfix + " ";
                    go = Instantiate(spawnedPrefab.prefab, (Vector3)position, rotation);
                    spawned.Add(go);
                    spawnedPrefab.prefab.name = name;

                    if (spawnedPrefab.stopSpawning)
                    {
                        break;
                    }
                }
                name = "";
            }

            return(spawned.ToArray());
        }
コード例 #31
0
    private static int CalculateWin(float attackArmy, float defendArmy, float escalationRate, int luck = 4)
    {
        int result = 4;

        if (attackArmy > defendArmy)
        {
            result--;
        }

        if (escalationRate > 0.5f)
        {
            result--;
        }

        for (int i = 0; i < luck; i++)
        {
            if (Random.Range(0f, 1f) > 0.4f)
            {
                result--;
            }
        }
        result = Mathf.Clamp(result, 1, 4);
        return(result);
    }
コード例 #32
0
    private int GetRandomWaypoint(Tuple <int, float>[] weightIndecies)
    {
        // Calculate the total weight we have to deal with and the cumulative weight up to that point.
        float totalWeight = 0;

        Tuple <int, float>[] cumulative = new Tuple <int, float> [weightIndecies.Length];
        for (int i = 0; i < weightIndecies.Length; i++)
        {
            cumulative[i] = new Tuple <int, float>(weightIndecies[i].Item1, totalWeight += weightIndecies[i].Item2);
        }

        float target = Random.Range(0, totalWeight);

        // Find the value that encompasses the target.
        foreach (Tuple <int, float> weightIndex in cumulative)
        {
            if (weightIndex.Item2 > target)
            {
                return(weightIndex.Item1);
            }
        }

        throw new Exception("Error getting random waypoint.");
    }
コード例 #33
0
    private GameObject RandomizeCharacterEvent(RoomStats.RoomType roomName)
    {
        List <GameObject> eligibleEvents = new List <GameObject>();

        for (int i = 0; i < campMan.GetCharacterEvents().Count; i++)
        {
            CharacterEvent charEvent = campMan.GetCharacterEvents()[i].GetComponent <CharacterEvent>();

            if (charEvent.MatchesRoomType(roomName) &&          /*&& charEvent.playedOnce == false*/
                HasRequiredStats(charEvent.requiredStats, true))
            {
                eligibleEvents.Add(campMan.GetCharacterEvents()[i]);
            }
        }

        int        randNum   = Random.Range(0, eligibleEvents.Count);
        GameObject thisEvent = eligibleEvents[randNum];

        campMan.playedEvents.Add(thisEvent);
        campMan.charEvents.Remove(thisEvent);
        //campMan.RemoveFromCharEvents(thisEvent);

        return(thisEvent);
    }
コード例 #34
0
ファイル: GameScript.cs プロジェクト: GlenDC/MassiveBullet
    void Start()
    {
        Initialize();

        config = GameScript.GetConfig();

        Screen.lockCursor = true;

        random = new UnityEngine.Random();

        CurrentPauseTime = MAX_PAUSE_TIME / 2.0f;
    }
コード例 #35
0
    /// <summary>
    /// Get the value of tickets sold for a specific screen
    /// </summary>
    /// <param name="screen">The Screen object to get the tickets for</param>
    /// <returns>The value of tickets sold</returns>
    public int GetTicketsSoldValue(ScreenObject screen)
    {
        UnityEngine.Random ran = new UnityEngine.Random();
        int min = (int)(screen.GetNumSeats() / 1.5);  // this will be affected by the posters etc, and rep
        int max = screen.GetNumSeats();
        int ticketsSold = UnityEngine.Random.Range(min, max);
        float repMultiplier = customerController.reputation.GetMultiplier();
        ticketsSold = 3 + (int)(ticketsSold * repMultiplier);

        return ticketsSold;
    }
コード例 #36
0
ファイル: GameLogic.cs プロジェクト: Lindet/UnitySnake
	private Vector2 GetCoordinates()
	{
		var rnd = new Random ();
		var vector = new Vector2();
		bool freePlace = false;
		float x, y;

		while (!freePlace) {
            x = Mathf.Round(Random.Range(globals.leftWall + 0.1f, globals.rightWall - 0.1f)*10)/10;
            y = Mathf.Round(Random.Range(globals.topWall - 0.1f, globals.bottomWall + 0.1f)*10)/10;
			freePlace = Check(x,y);
		    if (freePlace) vector = new Vector3(x, y);

		}
		return vector;
	}
コード例 #37
0
ファイル: Global.cs プロジェクト: markofevil3/SlotMachine
	public static void Init() {
	  systemRandom = new System.Random();
	  unityRandom = new UnityEngine.Random();
	}
コード例 #38
0
ファイル: Player.cs プロジェクト: hankyates/survive
 void ShuffleCards()
 {
     var r = new UnityEngine.Random();
     var totalPoints = cardDefs.Cards.Sum(c => c.Points);
     while(cards.Count < lifeIndex[lifeLevel]) {
         var num = UnityEngine.Random.Range(0, totalPoints);
         foreach(var c in cardDefs.Cards) {
             num -= c.Points;
             if (num <= 0) {
                 cards.Add(c);
                 break;
             }
         }
     }
 }
コード例 #39
0
 private string getRandomAnswer(List<string> answers)
 {
     UnityEngine.Random rand = new UnityEngine.Random();
     int randIndex = UnityEngine.Random.Range(0, (answers.Count - 1));
     return answers[randIndex];
 }