Beispiel #1
0
        /// <summary>
        /// Being called each frame to check if is still touched ('pressed')
        /// </summary>
        /// <param name="touchRect">A small rectangle around the touch position if available</param>
        /// <returns>True if is still pressed. False otherwise</returns>
        private bool CheckIfStillTouching(Rectangle?touchRect)
        {
            bool isStillTouching = false;

            if (touchRect != null)
            {
                isStillTouching = ScreenBounds.Intersects(touchRect.Value);
            }

            return(isStillTouching);
        }
 private void Awake()
 {
     m_rigidbody2D = GetComponent<Rigidbody2D>();
     m_transform = transform;
     m_spriteRenderer = GetComponent<SpriteRenderer>();
     var screenBounds = new ScreenBounds(Camera.main);
     float halfRendererWidth = m_spriteRenderer.bounds.size.x / 2f;
     float halfRendererHeight = m_spriteRenderer.bounds.size.y / 2f;
     m_positionBoundsX = new Range<float>(screenBounds.UpperLeft.x + halfRendererWidth, screenBounds.UpperRight.x - halfRendererWidth);
     m_positionBoundsY = new Range<float>(screenBounds.BottomLeft.y + halfRendererHeight, screenBounds.UpperLeft.y - halfRendererHeight);
 }
Beispiel #3
0
        /// <summary>
        /// Being called each frame to check if was just pressed
        /// </summary>
        /// <param name="touchRect">A small rectangle around the touch position if available</param>
        /// <returns>True if was pressed in the current game frame. False otherwise</returns>
        private bool CheckIfFirstTouchDown(Rectangle?touchRect)
        {
            bool isFirstTouched = false;

            if (!isTouched && touchRect != null)
            {
                isFirstTouched = ScreenBounds.Intersects(touchRect.Value);
            }

            return(isFirstTouched);
        }
    private void Start()
    {
        //Get static singleton as this ScreenBounds
        instance = GetComponent <ScreenBounds>();

        //Get connected boxCollider2D
        _boxCollider = GetComponent <BoxCollider2D>();

        //Find max and min X coordinates as max and min of collider bounds
        MaxXCoordinate = _boxCollider.bounds.max.x;
        MinXCoordinate = _boxCollider.bounds.min.x;
    }
    private void Start()
    {
        spriteRenderer = GetComponent <SpriteRenderer>();

        currentTarget = ScreenBounds.GetRandomPosition();
        shotDelay     = new WaitForSeconds(shotdelayTime);
        angerDelay    = new WaitForSeconds(angerdelayTime);
        shotSpeedxN   = shotSpeed * 2.5f;

        StartCoroutine(AngerCountDown());
        StartCoroutine(OpenFire());
    }
Beispiel #6
0
    private void Start()
    {
        enemies         = new List <GameObject>();
        screenBounds    = GetBounds();
        enemiesToRemove = new List <GameObject>();

        currentEnemyWeights = new float[enemyPrefabs.Length];
        for (int i = 0; i < currentEnemyWeights.Length; i++)
        {
            currentEnemyWeights[i] = enemyWeightLimits[i].firstPerc;
        }
    }
Beispiel #7
0
 public static ScreenBounds GetScreenBounds()
 {
     const float bound = 0f;
     ScreenBounds bounds = new ScreenBounds();
     TerrainControls element = s_terrainComponents[0];
     bounds.left = element.transform.position.x+bound;
     bounds.bottom = element.transform.position.y+bound;
     bounds.top = element.transform.position.x+element.GetComponent<TerrainEditor2D>().Height-bound;
     element = s_terrainComponents[s_terrainComponents.Count - 1];
     bounds.right = element.transform.position.x + element.GetComponent<TerrainEditor2D>().Width-bound;
     return bounds;
 }
Beispiel #8
0
 private IEnumerator SpawnPowerUp()
 {
     while (true)
     {
         int               index         = UnityEngine.Random.Range(0, powerUpPrefabs.Length);
         Vector2           spawnPosition = ScreenBounds.RandomTopPosition();
         PowerupController powerup       = Instantiate(powerUpPrefabs[index], spawnPosition, Quaternion.identity);
         // Adding an Observer
         AddObserver(powerup);
         yield return(new WaitForSeconds(UnityEngine.Random.Range(currentLevel.powerUpMinimumWait, currentLevel.powerUpMaximumWait)));
     }
 }
Beispiel #9
0
        protected override void OnGesture(Gesture gesture)
        {
            if (_currentTileset == null)
            {
                return;
            }

            switch (gesture.GestureType)
            {
            case GestureType.Down:

                if (_touchId == 0 && ScreenBounds.Contains(gesture.Origin))
                {
                    _touchId   = gesture.TouchId;
                    _selection = null;
                    _origin    = null;

                    Select(gesture);

                    if (_selection.HasValue)
                    {
                        _origin = _selection.Value.Location;
                    }
                }

                break;

            case GestureType.Move:

                if (_touchId == gesture.TouchId)
                {
                    Select(gesture);
                }

                break;

            case GestureType.CapturedByOther:
            case GestureType.Up:
                if (_touchId == gesture.TouchId)
                {
                    if (gesture.GestureType == GestureType.Up && _selection.HasValue)
                    {
                        CreateToolFromSelection();
                    }

                    _touchId   = 0;
                    _selection = null;
                    _origin    = null;
                }
                break;
            }
        }
Beispiel #10
0
    public EnemySpawner(IAssetDispenser assetDispenser, ScreenBounds bounds,
                        ISessionEventsListener eventListener)
    {
        this.assetDispenser = assetDispenser;
        this.boundsChecker  = bounds;
        this.eventListener  = eventListener;

        foreach (var preset in Settings.SpawnSettings)
        {
            spawned[preset.GroupId]       = new HashSet <Enemy>();
            spawnCapCount[preset.GroupId] = preset.StartCopiesCount;
        }
    }
Beispiel #11
0
    private void MoveProjectile()
    {
        transform.Translate(projectileDirection * Time.deltaTime * projectileSpeed, Space.World);

        if (ScreenBounds.OutOfBounds(transform.position))
        {
            if (isPlayers)
            {
                EventBroker.CallProjectileOutOfBounds();
            }
            Destroy(gameObject);
        }
    }
Beispiel #12
0
    //Controls the thrusters and applys movement to the ship
    private void MoveShip()
    {
        //Get new velocity vector after applying user input
        if (Input.GetButton("Thrust"))
        {
            CurrentVelocity += transform.up * ThrusterPower * Time.deltaTime;
        }

        //Start looping the thruster sound effect if we arent
        if (Input.GetButton("Thrust") && !PlayingThrusterSound)
        {
            ThrusterRenderer.forceRenderingOff = false;
            PlayingThrusterSound = true;
            SoundPlayer.UnPause();
        }
        //Otherwise stop looping if it shouldnt be anymore
        else if (!Input.GetButton("Thrust") && PlayingThrusterSound)
        {
            ThrusterRenderer.forceRenderingOff = true;
            PlayingThrusterSound = false;
            SoundPlayer.Pause();
        }

        //Clamp velocity magnitude
        if (CurrentVelocity.magnitude < 0.0f)
        {
            CurrentVelocity = Vector3.ClampMagnitude(CurrentVelocity, VelocityRange.x);
        }
        else if (CurrentVelocity.magnitude > 0.0f)
        {
            CurrentVelocity = Vector3.ClampMagnitude(CurrentVelocity, VelocityRange.y);
        }

        //Apply friction
        if (CurrentVelocity.magnitude > 0.0f)
        {
            CurrentVelocity -= CurrentVelocity.normalized * FrictionStrength * Time.deltaTime;
        }
        if (CurrentVelocity.magnitude < 0.0f)
        {
            CurrentVelocity += CurrentVelocity.normalized * FrictionStrength * Time.deltaTime;
        }

        //Get new location value for the ship, kept inside the screen borders
        Vector3 NewPos = transform.position + CurrentVelocity * Time.deltaTime;

        NewPos = ScreenBounds.WrapPosInside(NewPos);

        //Move to the new location
        transform.position = NewPos;
    }
    private void ScreenWrap(ScreenBounds bounds)
    {
        Vector3 relativeLoc = bounds.transform.InverseTransformPoint(transform.position);

        if (Mathf.Abs(relativeLoc.x) > 0.5f)
        {
            relativeLoc.x *= -1;
        }
        if (Mathf.Abs(relativeLoc.y) > 0.5f)
        {
            relativeLoc.y *= -1;
        }
        transform.position = bounds.transform.TransformPoint(relativeLoc);
    }
Beispiel #14
0
    private void SpawnParentAsteroid(int index)
    {
        AsteroidController asteroid = AsteroidController.SpawnAsteroid();
        Vector3            spawnLocation;

        do
        {
            spawnLocation = ScreenBounds.RandomLocationOnScreen();
        } while ((spawnLocation - PlayerShipController.POSITION).magnitude < MIN_DISTANCE_AST_FROM_SHIP);
        asteroid.transform.position = spawnLocation;
        asteroid.transform.rotation = Random.rotation;
        asteroid.asteroidSize       = currentLevel.initialAsteroidSize;
        asteroid.gameObject.name    = "Asteroid_" + index.ToString("00");
    }
Beispiel #15
0
    private void ScreenWrap()
    {
        if (!enabled)
        {
            return;
        }

        bool isOutOfBounds = ScreenBounds.OutOfBounds(new Vector2(Mathf.Abs(transform.position.x) - halfObjectWidth, Mathf.Abs(transform.position.y) - halfObjectHeight));

        // if object is visable then no need to screen wrapp
        if (!isOutOfBounds)
        {
            isWrappingX = false;
            isWrappingY = false;
            return;
        }

        // if already true, no need to screen wrap
        if (isWrappingX && isWrappingY)
        {
            return;
        }

        var     cam         = Camera.main;
        Vector3 newPosition = transform.position;

        bool isXOutOfBounds = ScreenBounds.IsXOutOfBounds(new Vector2(transform.position.x + halfObjectWidth, transform.position.y + halfObjectHeight));
        bool IsYOutOfBounds = ScreenBounds.IsYOutOfBounds(new Vector2(transform.position.x + halfObjectWidth, transform.position.y + halfObjectHeight));

        // if not wrapped already or off screen and x is out of bounds
        if (!isWrappingX && isXOutOfBounds)
        {
            // cam position is x=0, y=0 and thus scene is laid out like mirror
            // everything to left is neg coords, right is positive coords
            // so can just add - to reverse the position
            newPosition.x = -newPosition.x;

            // this helps if there is lag of mirroring the position or if switched multiple times
            isWrappingX = true;
        }

        if (!isWrappingY && IsYOutOfBounds)
        {
            newPosition.y = -newPosition.y;
            isWrappingY   = true;
        }

        transform.position = newPosition;
    }
Beispiel #16
0
    void SpawnEnemy()
    {
        int        EnemyIndex = Random.Range(0, m_EnemyDB.Count);
        GameObject enemy      = Instantiate(m_EnemyDB[EnemyIndex]) as GameObject;

        float   enemyBBy     = enemy.GetComponent <SpriteRenderer>().bounds.size.y;
        Vector2 screenBounds = ScreenBounds.GetScreenBounds();
        float   yPosition    = Random.Range(-screenBounds.y + enemyBBy / 2, screenBounds.y - enemyBBy / 2);

        float speed = Random.Range(minSpeed, maxSpeed);


        enemy.transform.position = new Vector2(screenBounds.x * 1.5f, yPosition);
        enemy.GetComponent <BasicEnemy>().SetSpeed(speed);
    }
Beispiel #17
0
    private void MovePlayer()
    {
        float horizontalMovement = Input.GetAxis("Horizontal");

        if (Mathf.Abs(horizontalMovement) > Mathf.Epsilon)
        {
            horizontalMovement  = horizontalMovement * Time.deltaTime * runningSpeed;
            horizontalMovement += transform.position.x;

            float limit =
                Mathf.Clamp(horizontalMovement, ScreenBounds.left(), ScreenBounds.right());

            transform.position = new Vector2(limit, transform.position.y);
        }
    }
Beispiel #18
0
    void SpawnPowerUp()
    {
        int        powerUpIndex = Random.Range(0, m_OtherDB.Count);
        GameObject powerUp      = Instantiate(m_OtherDB[powerUpIndex]) as GameObject;

        float   otherBBy     = powerUp.GetComponent <SpriteRenderer>().bounds.size.y;
        Vector2 screenBounds = ScreenBounds.GetScreenBounds();
        float   yPosition    = Random.Range(-screenBounds.y + otherBBy / 2, screenBounds.y - otherBBy / 2);

        float speed = -Random.Range(minSpeed, maxSpeed);

        powerUp.transform.position = new Vector2(screenBounds.x * 1.5f, yPosition);

        powerUp.GetComponent <Rigidbody2D>().velocity = new Vector2(speed, 0.0f);
    }
Beispiel #19
0
    //Rotates the spawn direction vector, then returns the spawn location for the next asteroid
    private Vector3 GetNextSpawnPos()
    {
        //Get the furthest possible spawn location in the current direction, then calcuate its distance from the center
        Vector3 MaxDistanceSpawnPos = SpawnDirection * SpawnDistanceRange.y;

        MaxDistanceSpawnPos = ScreenBounds.ClampPosInside(MaxDistanceSpawnPos);
        float MaxSpawnDistance = Vector3.Distance(Vector3.zero, MaxDistanceSpawnPos);
        //Get the new spawn pos somewhere along that line
        float   SpawnDistance = Random.Range(SpawnDistanceRange.x, MaxSpawnDistance);
        Vector3 SpawnPos      = SpawnDirection * SpawnDistance;

        //Rotate the spawn direction ready for next time, then return the final spawn position
        SpawnDirection = Quaternion.AngleAxis(-RotationPerSpawn, Vector3.forward) * SpawnDirection;
        return(SpawnPos);
    }
Beispiel #20
0
    void spawnPlanet(int idx)
    {
        if (idx < planets.planets.Length && idx >= 0)
        {
            GameObject planet = Instantiate(planets.planets[idx].planetGameObject) as GameObject;

            Vector2 screenBounds = ScreenBounds.GetScreenBounds();
            float   xPosition    = screenBounds.x * 1.2f;
            float   yPosition    = 0;
            float   zPosition    = 9;

            planet.transform.position = new Vector3(xPosition, yPosition, zPosition);
            planet.GetComponent <Rigidbody2D>().velocity = new Vector2(-speed, 0);
        }
    }
Beispiel #21
0
    // Start is called before the first frame update
    void Start()
    {
        S = this;

        cam = Camera.main;
        if (!cam.orthographic)
        {
            Debug.LogError("ScaleToCamera:Start() - Camera.main needs to be orthographic" + "for ScaleToCamera to work, but this camera is not orthographic.");
        }

        boxColl      = GetComponent <BoxCollider>();
        boxColl.size = Vector3.one;

        transform.position = Vector3.zero;
        ScaleSelf();
    }
    private void MoveProjectile()
    {
        transform.Translate(projectileDirection * Time.deltaTime * projectileSpeed, Space.World);

        if (ScreenBounds.OutOfBounds(transform.position))
        {
            if (isPlayers == true)
            {
                if (ProjectileOutOfBounds != null)
                {
                    ProjectileOutOfBounds();
                }
            }
            Destroy(gameObject);
        }
    }
Beispiel #23
0
 public bool AcceptsMouseEvent(MouseState mouse)
 {
     if (!Visible)
     {
         return(false);
     }
     if (!InteractionEnabled)
     {
         return(false);
     }
     if (!ScreenBounds.Contains(new Point(mouse.X, mouse.Y)))
     {
         return(false);
     }
     return(true);
 }
    private void OnTriggerExit(Collider other)
    {
        if (!enabled)
        {
            return;
        }

        ScreenBounds bounds = other.GetComponent <ScreenBounds>();

        if (bounds == null)
        {
            return;
        }

        ScreenWrap(bounds);
    }
Beispiel #25
0
    private void ScreenWrap(ScreenBounds bounds)
    {
        // Wrap whichever direction is necessary.
        Vector3 relativeLoc = bounds.transform.InverseTransformPoint(transform.position);

        // relativeLoc is in the local coords of OnScreenBounds, 0.5f is the screen edge.
        if (Mathf.Abs(relativeLoc.x) > 0.5f)
        {
            relativeLoc.x *= -1;
        }
        if (Mathf.Abs(relativeLoc.y) > 0.5f)
        {
            relativeLoc.y *= -1;
        }
        transform.position = bounds.transform.TransformPoint(relativeLoc);
    }
Beispiel #26
0
 public override void Update(GameTime gameTime)
 {
     if (ScreenBounds.Contains(currentGame.inputManager.mouseState.Position))
     {
         col = Color.White;
         if (currentGame.inputManager.mouseState.LeftButton == ButtonState.Pressed && currentGame.inputManager.oldMouseState.LeftButton == ButtonState.Released)
         {
             col = Color.Gray;
             currentGame.inputManager.currentRightUse = InputManager.RightButtonUse.PlaceHouse;
         }
     }
     else
     {
         col = Color.LightGray;
     }
 }
Beispiel #27
0
    private float RotationPerSpawn;                           //Spawn direction vector rotation after each spawn

    private void Start()
    {
        //Spawn all the stars into place
        RotationPerSpawn = 360f / StarAmount;
        for (int i = 0; i < StarAmount; i++)
        {
            //Get the furthest distance possible spawn location in the current spawn direction, then calculate its distance
            Vector3 MaxDistanceSpawnPos = SpawnDirection * MaxSpawnDistance;
            MaxDistanceSpawnPos = ScreenBounds.ClampPosInside(MaxDistanceSpawnPos);
            float MaxValidSpawnDistance = Vector3.Distance(Vector3.zero, MaxDistanceSpawnPos);
            //Spawn a new star in a random distance between 0 and this max distance
            float   RandomSpawnDistance = Random.Range(0f, MaxValidSpawnDistance);
            Vector3 SpawnPos            = SpawnDirection * RandomSpawnDistance;
            Instantiate(StarPrefab, SpawnPos, Quaternion.identity);
            //Rotate the spawn direction vector, ready for the next star to be spawned
            SpawnDirection = Quaternion.AngleAxis(-RotationPerSpawn, Vector3.forward) * SpawnDirection;
        }
    }
    void Start()
    {
        S = this;

        cam = Camera.main;
        // Camera must be orthographic for this to work.
        if (!cam.orthographic)
        {
            Debug.LogError("ScaleToCamera:Start() - Camera.main needs to be orthographic for ScaleToCamera to work, but this camera is not orthographic.");
        }

        boxColl = GetComponent <BoxCollider>();
        // Setting boxColl.size to 1 ensures other calculations will be correct.
        boxColl.size = Vector3.one;

        transform.position = Vector3.zero;
        ScaleSelf();
    }
Beispiel #29
0
    //Returns a position offset from the players current location, within the range of the given vector values
    private Vector3 GetOffsetPlayerPos(Vector2 OffsetRange)
    {
        //Get 2 random values within the given offset range to offset from the player pos in each direction
        float XOffset = Random.Range(OffsetRange.x, OffsetRange.y);
        float YOffset = Random.Range(OffsetRange.x, OffsetRange.y);

        //Flip a coin to decide which direction these offsets will be applied
        bool PositiveXOffset = Random.value >= 0.5f;
        bool PositiveYOffset = Random.value >= 0.5f;

        //Apply these offsets to the players current location to get the new offset position
        Vector3 OffsetPos = GameState.Instance.PlayerShip.transform.position;

        OffsetPos.x += PositiveXOffset ? XOffset : -XOffset;
        OffsetPos.y += PositiveYOffset ? YOffset : -YOffset;
        OffsetPos    = ScreenBounds.ClampPosInside(OffsetPos);
        return(OffsetPos);
    }
Beispiel #30
0
    void Start()
    {
        //set containers
        marbleContainer = new GameObject("Marbles");
        buttonContainer = new GameObject("Buttons");
        uiContainer     = new GameObject("UserInterface");

        //utility handle setting
        colorPalette = Palette.palette;
        bounds       = GameObject.Find("Main Camera").GetComponent <ScreenBounds>();

        //generate palette
        paletteLenght = ShortTermMemory.memory.ChangeColorsNumber(0);
        colorPalette.GeneratePalette(paletteLenght);

        //generate user and cpu marbles and positioning
        numberOfMarbles = ShortTermMemory.memory.ChangeMarblesNumber(0);
        GenerateSet();
    }
Beispiel #31
0
    // This is called whenever this GameObject exits the bounds of OnScreenBounds
    private void OnTriggerExit(Collider other)
    {
        // NOTE: OnTriggerExit is still called when this.enabled==false
        if (!enabled)
        {
            return;
        }

        // Ensure that the other is OnScreenBounds
        ScreenBounds bounds = other.GetComponent <ScreenBounds>();

        if (bounds == null)
        {
            // Check for runaway GameObjects using ExtraBounds child of ScreenBounds
            bounds = other.GetComponentInParent <ScreenBounds>();

            if (bounds == null) // If bounds is still null, give up and return
            {
                return;
            }
            else
            {
                // Move this GameObject closer to ScreenBounds edges, making use
                //  of the ComponentDivision extension method in Vector3Extensions
                Vector3 pos = transform.position.ComponentDivide(other.transform.localScale);
                pos.z = 0; // Make sure it's in the z=0 plane.
                transform.position = pos;
                Debug.LogWarning("OffScreenWrapper:OnTriggerExit() - Runaway object caught by ExtraBounds: "
                                 + gameObject.name);
            }
        }

        ScreenWrap(bounds);


#if DEBUG_AnnounceOnTriggerExit
        // GetComponent is pretty slow, but because this is in a debug test case and only happens once every few seconds, it's okay here.
        if (GetComponent <Asteroid>() != null)
        {
            Debug.LogWarning(gameObject.name + " OnTriggerExit " + Time.time);
        }
#endif
    }
Beispiel #32
0
    //Causes a new target to be acquired when the current target has been reached, or the timer has expired
    private void UpdateTarget()
    {
        //Get a new target if we are close enough to the current target
        float TargetDistance = Vector3.Distance(transform.position, TargetPos);

        if (TargetDistance <= TargetUpdateDistance)
        {
            TargetPos        = ScreenBounds.GetInsidePos();
            NextTargetUpdate = Random.Range(TargetUpdateInterval.x, TargetUpdateInterval.y);
        }

        //Get a new target if the update timer expires
        NextTargetUpdate -= Time.deltaTime;
        if (NextTargetUpdate <= 0.0f)
        {
            TargetPos        = ScreenBounds.GetInsidePos();
            NextTargetUpdate = Random.Range(TargetUpdateInterval.x, TargetUpdateInterval.y);
        }
    }
Beispiel #33
0
 void Start()
 {
     m_bounds = TerrainControls.GetScreenBounds();
     m_ratio = (float)Screen.height / Screen.width;
 }