Beispiel #1
0
        /// <summary>
        /// Loads a structure from an XML element
        /// </summary>
        /// <param name="structure">XML element to load structure from</param>
        /// <param name="sheets">Spritesheets to preload for lower memory use</param>
        /// <returns>New Structure from XML data</returns>
        public static Structure LoadFromXML(XElement structure, List <Spritesheet> sheets = null)
        {
            string  structureID = structure.Element("StructureID").Value;
            Vector2 pos         = VectorEx.FromArray(structure.Element("Position").Value.Split(','));

            return(new Structure(pos, structureID, sheets));
        }
Beispiel #2
0
    private static List <Mesh> GenerateQuad(Vector2 topLeft, Vector2 topRight, Vector2 bottomLeft, Vector2 bottomRight)
    {
        Mesh        mesh     = new Mesh();
        List <Mesh> meshList = new List <Mesh>();

        mesh.vertices = new Vector3[] {
            VectorEx.Vec2ToVec3(topLeft),
            VectorEx.Vec2ToVec3(topRight),
            VectorEx.Vec2ToVec3(bottomRight),
            VectorEx.Vec2ToVec3(bottomLeft)
        };
        mesh.uv = new Vector2[] {
            topLeft,
            topRight,
            bottomRight,
            bottomLeft
        };
        mesh.triangles = new int[] {
            0, 1, 3,
            1, 2, 3
        };

        meshList.Add(mesh);
        return(meshList);
    }
Beispiel #3
0
        private void loadStructure(Vector2 position, string structureID)
        {
            elements = new List <Tuple <Rectangle, Vector2, string> >();
            bounds   = new List <RectangleF>();
            string    path = AppDomain.CurrentDomain.BaseDirectory + @"Content\structures\" + structureID + ".xml";
            XDocument doc  = XDocument.Load(path);                                            //open xml file

            foreach (XElement element in doc.Descendants("Structure").Descendants("Element")) //Go through each element of structure
            {
                //load rectangle and position from array
                Rectangle rect = RectangleEx.FromArray(element.Element("Rectangle").Value.Split(','));
                Vector2   pos  = VectorEx.FromArray(element.Element("Position").Value.Split(','));

                string sheetID = element.Element("spritesheet").Value;
                if (spritesheets.Count(s => s.SpritesheetID == sheetID) == 0)                //if preloaded sheets don't have necessary spritesheet
                {
                    spritesheets.Add(new Spritesheet(sheetID));
                }
                elements.Add(new Tuple <Rectangle, Vector2, string>(rect, pos, sheetID));
            }
            foreach (XElement element in doc.Descendants("Structure").Descendants("Bounds").Elements("Box"))
            {
                RectangleF boundary = RectangleF.FromArray(element.Value.Split(','));
                boundary.Location += position;
                bounds.Add(boundary);
            }
        }
 /// <summary>
 /// バイナリデータからオブジェクトを読み込みます。
 /// </summary>
 /// <param title="reader">読み込み元</param>
 public void ReadBinary(BinaryReader reader)
 {
     Exists = reader.ReadBoolean();
     if (Exists)
     {
         Position = VectorEx.ReadVector3(reader);
     }
 }
 /// <summary>
 /// オブジェクトをバイナリデータとして書き込みます。
 /// </summary>
 /// <param title="writer">書き込み先</param>
 public void WriteBinary(BinaryWriter writer)
 {
     writer.Write(Exists);
     if (Exists)
     {
         VectorEx.WriteVector3(writer, Position);
     }
 }
Beispiel #6
0
    void LateUpdate()
    {
        Vector2 playerDirection = VectorEx.Vec3ToVec2(playerTransform.position - transform.position).normalized;
        float   playerDistance  = Vector3.Distance(playerTransform.position, transform.position);
        Vector2 newPos          = playerDirection * Easing.easeInExpo(0f, 0.50f, Mathf.InverseLerp(4f, 1f, playerDistance));

        meshTransform.localPosition = VectorEx.Vec2ToVec3(newPos);
    }
 /// <summary>
 /// オブジェクトをバイナリデータとして書き込みます。
 /// </summary>
 /// <param title="writer">書き込み先</param>
 public void WriteBinary(BinaryWriter writer)
 {
     writer.Write(Exists);
     if (Exists)
     {
         VectorEx.WriteVector3(writer, Center);
         writer.Write(Radius);
     }
 }
 /// <summary>
 /// バイナリデータからオブジェクトを読み込みます。
 /// </summary>
 /// <param title="reader">読み込み元</param>
 public void ReadBinary(BinaryReader reader)
 {
     Exists = reader.ReadBoolean();
     if (Exists)
     {
         End = VectorEx.ReadVector3(reader);
         DirectionAndLength = VectorEx.ReadVector3(reader);
     }
 }
        public void ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                reader.Skip();
                return;
            }
            reader.ReadStartElement("MotionDataPlane");
            this.Exists = false;
            while (reader.NodeType != XmlNodeType.None)
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    break;
                }
                switch (reader.Name)
                {
                case "Points":
                    string lengthStr;
                    if (reader.IsEmptyElement || (lengthStr = reader.GetAttribute("Length")) == null)
                    {
                        reader.Skip();
                    }
                    else
                    {
                        reader.ReadStartElement("Points");
                        int length;
                        if (int.TryParse(lengthStr, out length) && length >= 3)
                        {
                            this.Exists = true;
                            this.Points = new Vector3[length];
                            string[] values = reader.ReadString().Split('\t');
                            for (int i = 0; i < length; i++)
                            {
                                Vector3 tmp;
                                if (VectorEx.TryParse(values, i * 3, out tmp))
                                {
                                    this.Points[i] = tmp;
                                }
                                else
                                {
                                    this.Exists = false;
                                    break;
                                }
                            }
                        }
                        reader.ReadEndElement();
                    }
                    break;

                default:
                    reader.Skip();
                    break;
                }
            }
            reader.ReadEndElement();
        }
 /// <summary>
 /// バイナリデータからオブジェクトを読み込みます。
 /// </summary>
 /// <param title="reader">読み込み元</param>
 public void ReadBinary(BinaryReader reader)
 {
     Exists = reader.ReadBoolean();
     if (Exists)
     {
         Center = VectorEx.ReadVector3(reader);
         Radius = reader.ReadSingle();
     }
 }
 /// <summary>
 /// オブジェクトをバイナリデータとして書き込みます。
 /// </summary>
 /// <param title="writer">書き込み先</param>
 public void WriteBinary(BinaryWriter writer)
 {
     writer.Write(Exists);
     if (Exists)
     {
         VectorEx.WriteVector3(writer, End);
         VectorEx.WriteVector3(writer, DirectionAndLength);
     }
 }
Beispiel #12
0
        public void ImportPoints()
        {
            var isSmile = recognizer == null ? ProgramCore.DefaultIsSmile : recognizer.IsOpenSmile;

            HeadPoints.Points.Clear();
            HeadPoints.Points.AddRange(VectorEx.ImportVector(isSmile));
            HeadPoints.IsVisible.AddRange(Enumerable.Repeat(true, HeadPoints.Points.Count));

            //headMorphing.Initialize(HeadPoints);
        }
Beispiel #13
0
 private void Start()
 {
     if (target != null)
     {
         if (VectorEx.IsNaN(offset2Target))
         {
             SetOffsetAsCurrent();
         }
         MoveCameraInPosition();
     }
 }
 /// <summary>
 /// バイナリデータからオブジェクトを読み込みます。
 /// </summary>
 /// <param title="reader">読み込み元</param>
 public void ReadBinary(BinaryReader reader)
 {
     Exists = reader.ReadBoolean();
     if (Exists)
     {
         Points = new Vector3[reader.ReadInt32()];
         for (int i = 0; i < Points.Length; i++)
         {
             Points[i] = VectorEx.ReadVector3(reader);
         }
     }
 }
 /// <summary>
 /// オブジェクトをバイナリデータとして書き込みます。
 /// </summary>
 /// <param title="writer">書き込み先</param>
 public void WriteBinary(BinaryWriter writer)
 {
     writer.Write(Exists);
     if (Exists)
     {
         writer.Write(Points.Length);
         for (int i = 0; i < Points.Length; i++)
         {
             VectorEx.WriteVector3(writer, Points[i]);
         }
     }
 }
    void PutOnGround()
    {
        var scr = SelfColliderRect;
        var offsetY2ObjectCenter = scr.center - transform.position.ToVector2();
        var bottomOrigin         = new Vector2(scr.center.x, scr.yMin);
        var groundPos            = StageUtility.FindGroundPosition(bottomOrigin);

        if (!VectorEx.IsNaN(groundPos))
        {
            var standPos = groundPos + Vector2.up * scr.height * .5f - offsetY2ObjectCenter;
            transform.position = standPos;
        }
    }
 protected void readPointsFromString(int length, string value)
 {
     string[] values = value.Split('\t');
     this.Points = new MotionDataPoint[length];
     for (int i = 0; i < length; i++)
     {
         Vector3 tmp;
         if (VectorEx.TryParse(values, i * 3, out tmp))
         {
             this.Points[i].Exists   = true;
             this.Points[i].Position = tmp;
         }
     }
 }
 protected void readLinesFromString(int length, string value)
 {
     string[] values = value.Split('\t');
     this.Lines = new MotionDataLine[length];
     for (int i = 0; i < length; i++)
     {
         Vector3 tmp1, tmp2;
         if (VectorEx.TryParse(values, i * 6, out tmp1) &&
             VectorEx.TryParse(values, i * 6 + 3, out tmp2))
         {
             this.Lines[i].Exists             = true;
             this.Lines[i].End                = tmp1;
             this.Lines[i].DirectionAndLength = tmp2;
         }
     }
 }
Beispiel #19
0
    protected override void DetectCollisions()
    {
        // Enemy collision detection
        RaycastHit hitInfo;
        var        ray  = new Ray(Origin, transform.rotation * Vector3.right);
        var        size = transform.localScale.x;

        if (transform.localScale.x <= 0.1f)
        {
            size = 0.1f;
        }
        if (Physics.Raycast(ray, out hitInfo, size * 2, 1 << 8))
        {
            if (hitInfo.collider.tag != "Enemy")
            {
                return;
            }

            OnCollide(hitInfo.collider, hitInfo.point);
            AlreadyHit.Remove(hitInfo.collider.gameObject);

            GetComponentInChildren <Stroboscope>().enabled = true;

            var collidee            = hitInfo.collider.transform;
            var lastCollidePosition = collidee.position;

            var cp    = ClosestPointOnRay(ray, lastCollidePosition - new Vector3(0, 0.4f, 0));
            var enemy = hitInfo.collider.GetComponent <Enemy>();
            var mat   = ColorShifting.Materials[ColorShifting.EnemyMaterials[enemy.GetType()]];
            if (enemy is SingleShotBehaviour && (enemy as SingleShotBehaviour).invertColors)
            {
                mat = ColorShifting.Materials["clr_Red"];
            }

            var go = (GameObject)Instantiate(CharginTemplate, cp, Quaternion.identity);
            go.transform.localScale += new Vector3(0.2f, 0.2f, 0.2f);
            go.FindChild("Sphere.2").renderer.material = mat;
            go.AddComponent <FlickerOut>();

            var hitPoint = collidee == null ? lastCollidePosition : collidee.position;

            var distance = Vector3.Distance(hitPoint, Origin);
            transform.localScale = VectorEx.Modulate(transform.localScale, new Vector3(0, 1, 1)) + (distance - 0.5f) / 2 * Vector3.right;
            transform.position   = Origin + (transform.rotation * Vector3.right) * transform.localScale.x;
        }
    }
 protected void ReadSpheresFromString(int length, string value)
 {
     string[] values = value.Split('\t');
     this.Spheres = new MotionDataSphere[length];
     for (int i = 0; i < length; i++)
     {
         Vector3 tmp1;
         float   tmp2;
         if (VectorEx.TryParse(values, i * 4, out tmp1) &&
             values.Length >= i * 4 + 3 &&
             float.TryParse(values[i * 4 + 3], out tmp2))
         {
             this.Spheres[i].Exists = true;
             this.Spheres[i].Center = tmp1;
             this.Spheres[i].Radius = tmp2;
         }
     }
 }
Beispiel #21
0
        /// <summary>
        /// Creates new button at a certain position with certain id, text, spritesheets to use for caching, and font
        /// </summary>
        /// <param name="position">Position of button</param>
        /// <param name="buttonText">Text on button</param>
        /// <param name="buttonID">ID of button</param>
        /// <param name="sheets">Location of button</param>
        /// <param name="font">Font to use to write on button</param>
        public Button(Vector2 position, string buttonText, string buttonID, List <Spritesheet> sheets = null, SpriteFont font = null)
        {
            XDocument doc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory +
                                           @"Content\menus\buttons\" + buttonID + ".xml");

            this.buttonID = buttonID;
            ButtonText    = buttonText;
            textFont      = font;

            if (sheets == null)
            {
                spriteSheets = new List <Spritesheet>();
            }
            else
            {
                spriteSheets = new List <Spritesheet>(sheets);
            }

            Vector2 size = VectorEx.FromArray(doc.Descendants("Button").Elements("Size").First().Value.Split(','));

            buttonBounds = new Rectangle(position.ToPoint(), size.ToPoint());

            //get base image
            normalID = doc.Descendants("Button").Elements("Image").First().Value;
            if (spriteSheets.Count(sheet => sheet.SpritesheetID == normalID) == 0)
            {
                spriteSheets.Add(new Spritesheet(normalID));
            }

            //get hover image
            hoverID = doc.Descendants("Button").Elements("Hover").First().Value;
            if (spriteSheets.Count(sheet => sheet.SpritesheetID == hoverID) == 0)
            {
                spriteSheets.Add(new Spritesheet(hoverID));
            }

            //if there is no font loaded, use the default
            if (textFont == null)
            {
                textFont = RPG.ContentManager.Load <SpriteFont>(@"fonts\InterfaceFont");
            }

            lastState = Mouse.GetState();
        }
 protected void readCylindersFromString(int length, string value)
 {
     string[] values = value.Split('\t');
     this.Cylinders = new MotionDataCylinder[length];
     for (int i = 0; i < length; i++)
     {
         Vector3 tmp1, tmp2;
         float   tmp3;
         if (VectorEx.TryParse(values, i * 7, out tmp1) &&
             VectorEx.TryParse(values, i * 7 + 3, out tmp2) &&
             values.Length >= i * 7 + 6 &&
             float.TryParse(values[i * 7 + 6], out tmp3))
         {
             this.Cylinders[i].Exists = true;
             this.Cylinders[i].End    = tmp1;
             this.Cylinders[i].Axis   = tmp2;
             this.Cylinders[i].Radius = tmp3;
         }
     }
 }
Beispiel #23
0
    public override void OnDie()
    {
        if (Dead)
        {
            return;
        }

        base.OnDie();

        var go = (GameObject)Instantiate(ToSpawn.transform.parent.gameObject);

        go.transform.position   = transform.position;
        go.transform.localScale = VectorEx.Modulate(new Vector3(0.5967718f, 0.5967718f, 0.5967718f),
                                                    go.transform.localScale);
        go.FindChild(ToSpawn.name).GetComponent <PowerUpBehaviour>().enabled = true;

        go = (GameObject)Instantiate(BirdTemplate);
        go.transform.position = transform.position;

        Destroy(gameObject);
    }
        protected void loadContainer(string menuID)
        {
            slots = new List <Button> ();
            XDocument doc          = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + @"Content\menus\" + menuID + ".xml");
            var       containerXML = doc.Element("Menu").Element("Container");

            this.position = VectorEx.FromArray(containerXML.Element("Position").Value.Split(','));
            this.format   = (ContainerFormat)Enum.Parse(typeof(ContainerFormat), containerXML.Elements("Format").First().Value);
            string  slotID     = containerXML.Element("Slot").Value;
            string  style      = containerXML.Element("Style").Value;
            bool    rounded    = bool.Parse(containerXML.Element("Rounded").Value);
            Vector2 borderSize = VectorEx.FromArray(containerXML.Element("BorderSize").Value.Split(','));

            this.columns = int.Parse(containerXML.Element("Columns").Value);
            this.loadMenu(menuID);
            Vector2 baseSlot = new Button(Vector2.Zero, "", slotID).Size;

            if (format == ContainerFormat.Rectangle)
            {
                for (int i = 0; i < container.MaxCapacity; i++)
                {
                    int     x           = i % columns;
                    int     y           = i / columns;
                    Vector2 pos         = position + borderSize + new Vector2(x * baseSlot.X, y * baseSlot.Y);
                    Button  slot        = new Button(pos, "", slotID);
                    int     currentSlot = i;
                    slot.On_Click += (object sender, MouseState CurrentState) => SlotClick(currentSlot, CurrentState);
                    slots.Add(slot);
                }
                background = new Tile(
                    new Rectangle(position.ToPoint(),
                                  (borderSize * 2 + new Vector2(baseSlot.X * columns, baseSlot.Y * (float)Math.Ceiling((float)container.MaxCapacity / columns))).ToPoint()),
                    style, rounded);
            }
            else if (format == ContainerFormat.Armor)
            {
            }
        }
Beispiel #25
0
        private void loadCharacter(Vector2 position, string characterID)
        {
            frames = new Dictionary <Enum, int[]>();
            XDocument charDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + @"Content/characters/" + characterID + ".xml");

            //set speed values from xml file
            baseSpeed = double.Parse(charDoc.Descendants("Character").Elements("Speed").First().Value);
            speed     = baseSpeed;

            //set draw rectangle from xml file
            size          = VectorEx.FromArray(charDoc.Descendants("Character").Elements("Size").First().Value.Split(','));
            this.position = position;

            //set current direction from xml file
            currentDirection = (SpriteDirection)Enum.Parse(typeof(SpriteDirection), charDoc.Descendants("Character").Elements("Direction").First().Value);

            //set frame list from xml file
            foreach (XElement element in charDoc.Descendants("Character").Elements("Frame"))
            {
                Enum frameEnum;
                if (element.Element("Enum").Attribute("type").Value == "SpriteState")
                {
                    frameEnum = (SpriteState)Enum.Parse(typeof(SpriteState), element.Element("Enum").Value);
                }
                else
                {
                    frameEnum = (SpriteDirection)Enum.Parse(typeof(SpriteDirection), element.Element("Enum").Value);
                }
                List <int> frameIndexes = new List <int>();
                foreach (string index in element.Element("Value").Value.Split(','))
                {
                    frameIndexes.Add(int.Parse(index));
                }
                frames.Add(frameEnum, frameIndexes.ToArray());
            }
        }
Beispiel #26
0
        protected void loadMenu(string menuID)
        {
            sheets   = new List <Spritesheet>();
            elements = new List <IDrawable>();
            XDocument doc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + @"Content\menus\" + menuID + ".xml");

            doc.Descendants("Menu").Elements("Spritesheet").ToList().ForEach(element => sheets.Add(new Spritesheet(element.Value)));
            foreach (XElement element in doc.Descendants("Button"))
            {
                string  buttonID = element.Elements("ButtonID").First().Value;
                Vector2 position = VectorEx.FromArray(element.Elements("Position").First().Value.Split(','));
                string  text     = element.Elements("Text").First().Value;
                Button  temp     = new Button(position, text, buttonID, sheets);

                foreach (string methodString in element.Elements("Method"))
                {
                    temp.On_Click += (Button.ButtonClick)Delegate.CreateDelegate(typeof(Button.ButtonClick), this, methodString);
                }
                elements.Add(temp);
            }
            foreach (XElement element in doc.Descendants("Tiles"))
            {
            }
        }
Beispiel #27
0
        private void validateFloor()
        {
            if (_floorUpper == Vector3.Empty)
            {
                _floorUpper = new Vector3(0, 1, 0);
            }
            if (_floorParallel == Vector3.Empty)
            {
                _floorParallel = new Vector3(1, 0, 0);
            }
            _floorUpper.Normalize();
            _floorParallel.Normalize();
            float diff = Vector3.Dot(_floorUpper, _floorParallel);

            if (diff == 0)
            {
                _floorParallel = VectorEx.GetOneOfNormals(_floorUpper);
            }
            else
            {
                _floorParallel -= FloorUpper * diff;
                _floorParallel.Normalize();
            }
        }
Beispiel #28
0
        /// <summary>
        /// Creates list of all strucutures in area by reading from specified area id
        /// </summary>
        /// <param name="areaID">ID of area to load</param>
        /// <returns>List of drawable elements in array</returns>
        private void loadArea(string areaID)
        {
            XDocument doc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + @"Content\areas\" + areaID + ".xml");

            //create new lists for area
            drawElements = new List <IDrawable>();
            entities     = new List <Entity>();
            sheets       = new List <Spritesheet>();
            //create new eventboxes, replacing old ones if necessary
            if (boxes != null)
            {
                boxes.ForEach(box => box.UnloadBox());
            }
            boxes = new List <EventBox>();

            //loads main menu
            menu = new Menu(doc.Descendants("Area").Elements("Menu").First().Value);
            foreach (XElement element in doc.Descendants("Area").Descendants("Sheets").Descendants("SheetID"))
            {
                sheets.Add(new Spritesheet(element.Value));
            }

            if (doc.Descendants("Area").Elements("BGM").Count() > 0 &&
                doc.Descendants("Area").Elements("BGM").First().Element("MusicID").Value != "None")    //load bgm if is contained in xml
            {
                background = Content.Load <Song>("sound/music/" + doc.Descendants("Area").Elements("BGM").First().Element("MusicID").Value);
                if (MediaPlayer.State != MediaState.Playing || MediaPlayer.Queue.ActiveSong.Name != background.Name)
                {
                    MediaPlayer.Play(background);
                    MediaPlayer.Volume      = .3f;
                    MediaPlayer.IsRepeating = bool.Parse(doc.Descendants("Area").Elements("BGM").First().Element("Loop").Value);
                }
            }

            foreach (XElement element in doc.Descendants("Area").Descendants("Tile"))           //load tiles
            {
                drawElements.Add(Tile.LoadFromXML(element, sheets));
            }

            foreach (XElement element in doc.Descendants("Area").Descendants("Structure"))           //load structures
            {
                drawElements.Add(Structure.LoadFromXML(element, sheets));
            }

            foreach (XElement element in doc.Descendants("Area").Elements("Entity"))
            {
                EntityType      type      = (EntityType)Enum.Parse(typeof(EntityType), element.Element("Type").Value);
                SpriteDirection direction = (SpriteDirection)Enum.Parse(typeof(SpriteDirection), element.Element("Direction").Value);

                string entityID = element.Element("EntityID").Value;
                string name     = element.Element("Name").Value;

                RectangleF bounds = RectangleF.FromArray(element.Element("Bounds").Value.Split(','));

                string[] pos      = element.Element("Position").Value.Split(',');
                Vector2  position = new Vector2(float.Parse(pos[0]), float.Parse(pos[1]));

                EntitySpawnEventArgs args = new EntitySpawnEventArgs(entityID, name, type, 1, direction, position, bounds);
                Spawn(User, args);
            }

            foreach (XElement element in doc.Descendants("Area").Descendants("Player").Elements("EventBox"))           //load player event boxes
            {
                RectangleF         rect      = RectangleF.FromArray(element.Element("Box").Value.Split(','));
                EventBox.Condition condition = null;
                if (element.Elements("Condition").Count() > 0)
                {
                    string methodString = element.Element("Condition").Value;
                    condition = (EventBox.Condition)Delegate.CreateDelegate(typeof(EventBox.Condition), this, methodString);
                }
                if (element.Element("Method").Value == "OnNewAreaEnter")
                {
                    Vector2          position = VectorEx.FromArray(element.Element("Position").Value.Split(','));
                    NewAreaEventArgs args     = new NewAreaEventArgs(element.Element("AreaID").Value, position);
                    boxes.Add(new EventBox(User, rect, OnNewAreaEnter, args, condition));
                }
                else if (element.Element("Method").Value == "Spawn")
                {
                    int             maxNum    = int.Parse(element.Element("MaxNum").Value);
                    Vector2         position  = VectorEx.FromArray(element.Element("Position").Value.Split(','));
                    EntityType      type      = (EntityType)Enum.Parse(typeof(EntityType), element.Element("Type").Value);
                    SpriteDirection direction = (SpriteDirection)Enum.Parse(typeof(SpriteDirection), element.Element("Direction").Value);

                    EntitySpawnEventArgs args =
                        new EntitySpawnEventArgs(element.Element("EntityID").Value,
                                                 element.Element("Name").Value, type, maxNum, direction,
                                                 position, RectangleF.FromArray(element.Element("Bounds").Value.Split(',')));
                    boxes.Add(new EventBox(User, rect, Spawn, args, null));
                }
            }
        }
    void OnSceneGUI()
    {
        Transform targetTransform = editorTarget.transform;

        if (type == Type.PLANE)
        {
            Vector3[] outlinePoints = new Vector3[] { new Vector3(editorTarget.planeOutline.xMin, 0f, editorTarget.planeOutline.yMin),   // Bottom left
                                                      new Vector3(editorTarget.planeOutline.xMax, 0f, editorTarget.planeOutline.yMin),   // Bottom right
                                                      new Vector3(editorTarget.planeOutline.xMax, 0f, editorTarget.planeOutline.yMax),   // Top right
                                                      new Vector3(editorTarget.planeOutline.xMin, 0f, editorTarget.planeOutline.yMax),   // Top left
                                                      new Vector3(editorTarget.planeOutline.xMin, 0f, editorTarget.planeOutline.yMin) }; // Bottom left

            for (int i = 0; i < outlinePoints.Length; i++)                                                                               // Convert all points to world space
            {
                outlinePoints[i] = editorTarget.transform.TransformPoint(outlinePoints[i]);
            }

            Handles.color = Color.blue;
            Handles.DrawAAPolyLine(1f, outlinePoints);

            Handles.color = Color.white;
            Vector3 newPos;

            newPos = new Vector3(editorTarget.planeOutline.xMin, 0f, editorTarget.planeOutline.yMin);
            newPos = Handles.Slider2D(editorTarget.transform.TransformPoint(newPos),
                                      targetTransform.up, targetTransform.forward, targetTransform.right, 0.2f * HandleUtility.GetHandleSize(newPos), Handles.CubeCap, 0f);
            newPos = editorTarget.transform.InverseTransformPoint(newPos);
            editorTarget.planeOutline.xMin = newPos.x;
            editorTarget.planeOutline.yMin = newPos.z;

            newPos = new Vector3(editorTarget.planeOutline.xMax, 0f, editorTarget.planeOutline.yMin);
            newPos = Handles.Slider2D(editorTarget.transform.TransformPoint(newPos),
                                      targetTransform.up, targetTransform.forward, targetTransform.right, 0.2f * HandleUtility.GetHandleSize(newPos), Handles.CubeCap, 0f);
            newPos = editorTarget.transform.InverseTransformPoint(newPos);
            editorTarget.planeOutline.xMax = newPos.x;
            editorTarget.planeOutline.yMin = newPos.z;

            newPos = new Vector3(editorTarget.planeOutline.xMax, 0f, editorTarget.planeOutline.yMax);
            newPos = Handles.Slider2D(editorTarget.transform.TransformPoint(newPos),
                                      targetTransform.up, targetTransform.forward, targetTransform.right, 0.2f * HandleUtility.GetHandleSize(newPos), Handles.CubeCap, 0f);
            newPos = editorTarget.transform.InverseTransformPoint(newPos);
            editorTarget.planeOutline.xMax = newPos.x;
            editorTarget.planeOutline.yMax = newPos.z;

            newPos = new Vector3(editorTarget.planeOutline.xMin, 0f, editorTarget.planeOutline.yMax);
            newPos = Handles.Slider2D(editorTarget.transform.TransformPoint(newPos),
                                      targetTransform.up, targetTransform.forward, targetTransform.right, 0.2f * HandleUtility.GetHandleSize(newPos), Handles.CubeCap, 0f);
            newPos = editorTarget.transform.InverseTransformPoint(newPos);
            editorTarget.planeOutline.xMin = newPos.x;
            editorTarget.planeOutline.yMax = newPos.z;
        }

        // Render lines and edit spheres for the shape

        Line2D[] outline = shapeOutline.GetOutline();

        for (int i = 0; i < outline.Length; i++)
        {
            Line2D  line  = outline[i];
            Vector3 start = targetTransform.TransformPoint(VectorEx.Vec2ToVec3(line.start));
            Vector3 end   = targetTransform.TransformPoint(VectorEx.Vec2ToVec3(line.end));
            Handles.color = Color.white;
            Handles.DrawLine(start, end);

            Handles.color = Color.green;
            Vector3 buttonPos = Vector3.Lerp(start, end, 0.5f);
            if (Handles.Button(buttonPos, targetTransform.rotation, 0.15f * HandleUtility.GetHandleSize(buttonPos), 0.2f * HandleUtility.GetHandleSize(buttonPos), Handles.SphereCap))
            {
                shapeOutline.InsertPointAtIndex(VectorEx.Vec3ToVec2(targetTransform.InverseTransformPoint(buttonPos)), i + 1);
            }
        }

        Vector2[] points = shapeOutline.GetPoints();
        for (int i = 0; i < points.Length; i++)
        {
            Vector3 worldPos = targetTransform.TransformPoint(VectorEx.Vec2ToVec3(points[i]));

            Handles.color = Color.blue;
            Vector3 newPos          = Handles.Slider2D(worldPos, targetTransform.up, targetTransform.forward, targetTransform.right, 0.25f * HandleUtility.GetHandleSize(worldPos), Handles.SphereCap, 1f);
            Vector3 deleteButtonPos = worldPos + QuaternionEx.GetRightVector(SceneView.lastActiveSceneView.rotation) * 0.15f * HandleUtility.GetHandleSize(worldPos)
                                      + QuaternionEx.GetUpVector(SceneView.lastActiveSceneView.rotation) * 0.15f * HandleUtility.GetHandleSize(worldPos);

            newPos = targetTransform.InverseTransformPoint(newPos);
            Vector2 newPos2D = VectorEx.Vec3ToVec2(newPos);

            if (!Mathf.Approximately(points[i].x, newPos2D.x) ||
                !Mathf.Approximately(points[i].y, newPos2D.y))
            {
                shapeOutline.SetPointAtIndex(newPos2D, i);
            }

            Handles.color = Color.red;
            if (Handles.Button(deleteButtonPos, targetTransform.rotation, 0.05f * HandleUtility.GetHandleSize(deleteButtonPos), 0.05f * HandleUtility.GetHandleSize(deleteButtonPos), Handles.DotCap))
            {
                shapeOutline.RemovePointAtIndex(i);
            }
        }
    }
Beispiel #30
0
    void Update()
    {
        // var anyGamepad = Gamepads.Any;

        // Beat match
        SinceBeatMatch += Time.deltaTime;

        /*
         * if ( Keyboard.GetKeyState(KeyCode.Space) == ComplexButtonState.Pressed)
         * {
         * if (SinceBeatMatch < 2)
         * {
         *  BeatMatchPresses++;
         *  BeatMatchTotal += SinceBeatMatch;
         *  Pico.HeartbeatDuration = BeatMatchTotal / BeatMatchPresses;
         *  Pico.TimeLeftToHeartbeat = 0;
         * }
         * else
         * {
         *  BeatMatchTotal = 0;
         *  BeatMatchPresses = 0;
         * }
         *
         * SinceBeatMatch = 0;
         * }*/

        Ray   mouseRay  = Camera.main.ScreenPointToRay(Input.mousePosition);
        var   basePlane = new Plane(Vector3.up, new Vector3(0, ActualHeight - 0.5f, 0));
        float distance;

        switch (Pico.Phase)
        {
        case PlacingPhase.ChoosingPosition:
            if (Mouse.RightButton.State == MouseButtonState.Idle &&
                /* Keyboard.GetKeyState(KeyCode.LeftControl) == ComplexButtonState.Up &&*/
                basePlane.Raycast(mouseRay, out distance))
            {
                Vector3 p  = (Camera.main.transform.position + mouseRay.direction * distance).Round();
                var     hs = Pico.Level.Size / 2;

                var clampedPosition = p.Clamp(-Pico.Level.Size / 2, Pico.Level.Size / 2 - 1);
                if (Camera.main.transform.position.y < ActualHeight - 0.5f)
                {
                    clampedPosition.y++;
                }

                Anchor.transform.position = clampedPosition;

                if (Pico.Level.GetAccumulatorAt(clampedPosition) == null &&
                    Pico.Level.GetEmitterAt(clampedPosition) == null &&
                    Pico.Level.GetProjectorAt(clampedPosition) == null &&
                    Pico.Level.GetReceiverAt(clampedPosition) == null)
                {
                    if (p.x < -hs || p.x >= hs || p.y < -hs || p.y >= hs || p.z < -hs || p.z >= hs)
                    {
                        ;         // Do nothing
                    }
                    else if (Mouse.LeftButton.State == MouseButtonState.Clicked && !Pico.IsChangingLevel)
                    {
                        Pico.Phase = PlacingPhase.ChoosingDirection;
                    }
                }
            }

/*
 *              // Move up/down one layer
 *              if (( Keyboard.GetKeyState(KeyCode.W) == ComplexButtonState.Pressed) && DestinationHeight < Pico.Level.Size / 2 - 1)
 *              {
 *                  LastHeight = DestinationHeight;
 *                  DestinationHeight++;
 *                  EasingTimeLeft = 0;
 *              }
 *              if (( Keyboard.GetKeyState(KeyCode.S) == ComplexButtonState.Pressed) && DestinationHeight > -Pico.Level.Size / 2)
 *              {
 *                  LastHeight = DestinationHeight;
 *                  DestinationHeight--;
 *                  EasingTimeLeft = 0;
 *              }*/

            if (!Pico.IsChangingLevel)
            {    /*
                  * // Undo last placement
                  * if (AllPlacedProjectors.Count > 0 &&  (Keyboard.GetKeyState(KeyCode.Z) == ComplexButtonState.Pressed))
                  * {
                  *     var anchorAt = Pico.Level.GetProjectorAt(Anchor.transform.position);
                  *     if (anchorAt != null && AllPlacedProjectors.Contains(anchorAt))
                  *     {
                  *         Destroy(anchorAt);
                  *         AllPlacedProjectors.Remove(anchorAt);
                  *     }
                  *     else
                  *     {
                  *         Destroy(AllPlacedProjectors[AllPlacedProjectors.Count - 1]);
                  *         AllPlacedProjectors.RemoveAt(AllPlacedProjectors.Count - 1);
                  *     }
                  *
                  *     Pico.Level.PlacedCount--;
                  * }
                  *
                  * // Undo ALL placements
                  * if (Keyboard.GetKeyState(KeyCode.R) == ComplexButtonState.Pressed)
                  * {
                  *     Pico.Level.PlacedCount = 0;
                  *     Pico.RebootLevel();
                  * }
                  *
                  * if ( Keyboard.GetKeyState(KeyCode.Escape) == ComplexButtonState.Pressed)
                  * {
                  *     Pico.CycleLevels(Main.WorldMap);
                  * }*/
            }
            break;

        case PlacingPhase.ChoosingDirection:
            if (!Pico.IsChangingLevel)
            {
                // Undo last placement

                /*
                 * if ( Keyboard.GetKeyState(KeyCode.Z) == ComplexButtonState.Pressed)
                 * {
                 *  HighlightFace.GetComponentInChildren<Renderer>().enabled = false;
                 *  Pico.Phase = PlacingPhase.ChoosingPosition;
                 *  break;
                 * }*/
            }
            RaycastHit hitInfo;
            if (Anchor.collider.Raycast(mouseRay, out hitInfo, float.MaxValue))
            {
                HighlightFace.GetComponentInChildren <Transform>().LookAt(HighlightFace.transform.position +
                                                                          hitInfo.normal);
                HighlightFace.transform.position = Anchor.transform.position + hitInfo.normal * 0.5f;
                HighlightFace.GetComponentInChildren <Renderer>().enabled = true;

                if (Mouse.LeftButton.State == MouseButtonState.Clicked && !Pico.IsChangingLevel)
                {
                    Pico.Phase = PlacingPhase.ChoosingPosition;
                    HighlightFace.GetComponentInChildren <Renderer>().enabled = false;

                    var cellPosition = (Anchor.transform.position + VectorEx.New(Pico.Level.Size / 2)).Round();
                    //Debug.Log("Adding projector @ " + cellPosition);

                    AllPlacedProjectors.Add(Pico.Level.AddProjectorAt(
                                                (int)cellPosition.x, (int)cellPosition.y, (int)cellPosition.z,
                                                DirectionEx.FromVector(hitInfo.normal)));
                    Pico.Level.PlacedCount++;
                }
            }
            else
            {
                HighlightFace.GetComponentInChildren <Renderer>().enabled = false;

                if (Mouse.LeftButton.State == MouseButtonState.Clicked && !Pico.IsChangingLevel)
                {
                    if (basePlane.Raycast(mouseRay, out distance))
                    {
                        Vector3 p  = (Camera.main.transform.position + mouseRay.direction * distance).Round();
                        var     hs = Pico.Level.Size / 2;
                        if (p.x < -hs || p.x >= hs || p.y < -hs || p.y >= hs || p.z < -hs || p.z >= hs)
                        {
                            Pico.Phase = PlacingPhase.ChoosingPosition;
                        }
                    }
                    else
                    {
                        Pico.Phase = PlacingPhase.ChoosingPosition;
                    }
                }
            }
            break;
        }

        EasingTimeLeft += Time.deltaTime;
        float step = Mathf.Clamp01(EasingTimeLeft / EasingTime);

        Pico.GridHeight           = ActualHeight = Mathf.Lerp(LastHeight, DestinationHeight, Easing.EaseIn(step, EasingType.Quartic));
        Anchor.transform.position = new Vector3(Anchor.transform.position.x, DestinationHeight, Anchor.transform.position.z);

        GridParent.transform.position = new Vector3(-0.5f, ActualHeight - 0.5f, -0.5f);
    }