Пример #1
0
        public override void Shoot(NetworkPlayer player, Transform startPoint)
        {
            base.Shoot(player, startPoint);
            var from = startPoint.position;

            for (var i = 0; i < numPellets; i++)
            {
                var randomOffset_x = Random.Range(-(1 - accuracy), 1 - accuracy);
                var randomOffset_y = Random.Range(-(1 - accuracy), 1 - accuracy);
                var randomOffset_z = Random.Range(-(1 - accuracy), 1 - accuracy);

                var direction = transform.forward;

                direction.x += randomOffset_x;
                direction.y += randomOffset_y;
                direction.z += randomOffset_z;
                var endPoint = startPoint.position + direction * range;

                var didHit = Physics.Raycast(from, direction, out var hit, range, hittableMask);

                if (didHit)
                {
                    endPoint = hit.point;
                }

                ShootEffect(player, barrelPoint.position, endPoint, hit);

                hits[i] = BulletInfo.From(endPoint, damagePerBullet, hit);
            }

            player.Client.ShootMultiple(barrelPoint.position, hits);
        }
		public void BulletHitTest(BulletInfo n)
		{
			BulletHitTestCounter++;

			var p = n.Element.ToPoint();


			PrepareFilter();

			var query = from x in Filter(Items, n)
					where x.HitPoints > 0
					let distance = (x.Location - p).length
					where distance <= x.HitRange
					orderby distance
					select x;

			//DebugDump(
			//    new { counter = BulletHitTestCounter, targets = query.Count() }
			//    );

			var v = query.FirstOrDefault();

			if (v != null)
			{
				AddDamage.Chained(v, n.TotalDamage, n.Parent);

				n.Element.Orphanize();
			}
		}
Пример #3
0
        public void BulletHitTest(BulletInfo n)
        {
            BulletHitTestCounter++;

            var p = n.Element.ToPoint();


            PrepareFilter();

            var query = from x in Filter(Items, n)
                        where x.HitPoints > 0
                        let distance = (x.Location - p).length
                                       where distance <= x.HitRange
                                       orderby distance
                                       select x;

            //DebugDump(
            //    new { counter = BulletHitTestCounter, targets = query.Count() }
            //    );

            var v = query.FirstOrDefault();

            if (v != null)
            {
                AddDamage.Chained(v, n.TotalDamage, n.Parent);

                n.Element.Orphanize();
            }
        }
    public virtual BulletManager Create(Transform bulletParent, Transform barrelEnd, BulletInfo bulletInfo) //these are all used to create a bulletManager from the bulletInfo
    {
        BulletManager bulletManager = (BulletManager)CreateInstance(GetType());                             //I use GetType() here so that it will create a manager of the current class, not the base class

        bulletManager.Initialize(bulletParent, barrelEnd, bulletInfo);
        return(bulletManager);
    }
    protected override IEnumerator SpellZero()
    {
        yield return(new WaitForEndOfFrame());

        yield return(new WaitForEndOfFrame());

        float wait   = (animator.GetCurrentAnimatorStateInfo(0).length *animator.GetCurrentAnimatorStateInfo(0).speed);
        float offset = 0f;

        yield return(new WaitForSeconds(wait));

        for (int i = 0; i < 10; i++)
        {
            List <Vector3> startPositions = SimpleFunctions.RandomCircle(bulStartPoint.position, 0.5f, 18, offset);
            List <Vector3> endPositions   = SimpleFunctions.RandomCircle(bulStartPoint.position, 1.0f, 18, offset);
            for (int j = 0; j < startPositions.Count; j++)
            {
                BulletInfo bul    = new BulletInfo(startPositions[j], endPositions[j], bullet_speed, 1, 1, 1);
                Bullet     bullet = Instantiate(bulletObj, startPositions[j], Quaternion.identity).GetComponent <Bullet>();
                bullet.Setup(bul, 1, transform.rotation, false);
            }

            yield return(new WaitForSeconds(0.5f));

            offset += 5f;
        }
        yield return(new WaitForEndOfFrame());
    }
    public virtual BulletManager Create(Transform bulletParent, Transform barrelEnd, BulletInfo bulletInfo, IBulletContainer bulletContainer, EntityTeamManager teamManager, BulletSliderManager bulletSliderManager, PlayerModifiers playerModifiers)
    {
        BulletManager bulletManager = (BulletManager)CreateInstance(GetType());

        bulletManager.Initialize(bulletParent, barrelEnd, bulletInfo, bulletContainer, teamManager, bulletSliderManager, playerModifiers);
        return(bulletManager);
    }
    protected abstract IEnumerator AmmoRegen();     //this is for the CoRoutine to regenerate ammo

    #region Initializers/Create Methods

    private void Initialize(Transform bulletParent, Transform barrelEnd, BulletInfo bulletInfo)     //these are all the different variations of the initialize code
    {
        this.bulletParent = bulletParent;
        this.barrelEnd    = barrelEnd;
        this.bulletInfo   = bulletInfo;
        Initialize();
    }
Пример #8
0
 //弾を発射。
 public void Shot(BulletInfo info, Vector2 vec)
 {
     //発射。
     cannon.Shot(info, vec * (info.Speed / 5.0f));
     //弾薬を消費。
     armory.Remove(info.ID);
 }
Пример #9
0
    public void attack(Vector3 aim)
    {
        animator.SetBool("cool", true);
        StartCoroutine(Cool());
        if (atkRegister > 0)
        {
            return;
        }

        GameObject bulletObj = null;

        if (this.level == 1)
        {
            bulletObj = Instantiate(Bullet1, gameObject.transform.position, Quaternion.identity);
        }
        else if (this.level == 2)
        {
            bulletObj = Instantiate(Bullet2, gameObject.transform.position, Quaternion.identity);
        }
        else if (this.level == 3)
        {
            bulletObj = Instantiate(Bullet3, gameObject.transform.position, Quaternion.identity);
        }

        BulletInfo bulletInfo = null;

        bulletInfo = bulletObj.GetComponent <BulletInfo>();

        bulletInfo.arrow = (Vector3)((Vector2)aim - (Vector2)this.transform.position).normalized;
        float theta = Mathf.Sign(bulletInfo.arrow.y) * Mathf.Acos(Mathf.Abs(bulletInfo.arrow.x) / Mathf.Sqrt(bulletInfo.arrow.x * bulletInfo.arrow.x + bulletInfo.arrow.y * bulletInfo.arrow.y)) * Mathf.Rad2Deg;

        if (bulletInfo.arrow.x < 0)
        {
            theta = 180 - theta;
        }
        transform.localRotation = Quaternion.Euler(0, 0, 0);
        transform.Rotate(new Vector3(0, 0, theta + 90));

        bulletInfo.ad    = this.atk;
        bulletInfo.range = this.atkRange;
        bulletInfo.speed = this.bulletSpeed;

        if (this.level == 1)
        {
            bulletInfo.splash      = 0.1;
            bulletInfo.penetration = 1;
        }
        else if (this.level == 2)
        {
            bulletInfo.splash      = 0.2;
            bulletInfo.penetration = 3;
        }
        else if (this.level == 3)
        {
            bulletInfo.splash      = 0.2;
            bulletInfo.penetration = 5;
        }

        atkRegister = 60;
    }
Пример #10
0
        public Bullet(BulletInfo info, ProjectileArgs args)
        {
            Info = info;
            Args = args;

            if (info.Inaccuracy > 0)
            {
                var factor = ((Args.dest - Args.src).ToCVec().Length) / args.weapon.Range;
                Args.dest += (PVecInt) (info.Inaccuracy * factor * args.firedBy.World.SharedRandom.Gauss2D(2)).ToInt2();
                Log.Write("debug", "Bullet with Inaccuracy; factor: #{0}; Projectile dest: {1}", factor, Args.dest);
            }

            if (Info.Image != null)
            {
                anim = new Animation(Info.Image, GetEffectiveFacing);
                anim.PlayRepeating("idle");
            }

            if (Info.ContrailLength > 0)
            {
                Trail = new ContrailHistory(Info.ContrailLength,
                    Info.ContrailUsePlayerColor ? ContrailHistory.ChooseColor(args.firedBy) : Info.ContrailColor,
                    Info.ContrailDelay);
            }
        }
Пример #11
0
        public void DecodeBackwardCompatible_EverythingSet()
        {
            // Setup what we expect
            FontInfo expectedFontInfo = m_infoTable["TestStyle"].FontInfoForWs(-1);

            expectedFontInfo.m_fontName       = new InheritableStyleProp <string>("Algerian");
            expectedFontInfo.m_fontSize       = new InheritableStyleProp <int>(8000);
            expectedFontInfo.m_fontColor      = new InheritableStyleProp <Color>(Color.Red);
            expectedFontInfo.m_backColor      = new InheritableStyleProp <Color>(Color.White);
            expectedFontInfo.m_underline      = new InheritableStyleProp <FwUnderlineType>(FwUnderlineType.kuntNone);
            expectedFontInfo.m_underlineColor = new InheritableStyleProp <Color>(Color.Black);
            expectedFontInfo.m_bold           = new InheritableStyleProp <bool>(false);
            expectedFontInfo.m_italic         = new InheritableStyleProp <bool>(false);
            expectedFontInfo.m_superSub       = new InheritableStyleProp <FwSuperscriptVal>(FwSuperscriptVal.kssvOff);
            expectedFontInfo.m_offset         = new InheritableStyleProp <int>(0);

            // Here's the BLOB.
            // we got these values by looking at the memory when debugging Data Notebook.
            byte[] byteBlob = new byte[] { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00,
                                           0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
                                           0x00, 0x00, 0x06, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00,
                                           0x00, 0x08, 0x00, 0xff, 0x00, 0x00, 0x00, 0x09, 0x00, 0xff, 0xff, 0xff, 0x00,
                                           0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x00, 0x6c, 0x00, 0x67,
                                           0x00, 0x65, 0x00, 0x72, 0x00, 0x69, 0x00, 0x61, 0x00, 0x6e, 0x00, 0x00, 0x00 };
            string blob = new string(Encoding.Unicode.GetChars(byteBlob));

            BulletInfo bulletInfo = new BulletInfo();

            bulletInfo.EncodedFontInfo = blob;

            Assert.AreEqual(expectedFontInfo, bulletInfo.FontInfo);
        }
Пример #12
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Updates the bullet info.
        /// </summary>
        /// <param name="bulInfo">The bullet info.</param>
        /// ------------------------------------------------------------------------------------
        private void UpdateBulletInfo(ref BulletInfo bulInfo)
        {
            if (m_rbNone.Checked)
            {
                bulInfo.m_numberScheme = VwBulNum.kvbnNone;
            }
            else if (m_rbBullet.Checked)
            {
                bulInfo.m_numberScheme = (VwBulNum)((int)VwBulNum.kvbnBulletBase +
                                                    m_cboBulletScheme.SelectedIndex);
                bulInfo.FontInfo = m_BulletsFontInfo;
            }
            else if (m_rbNumber.Checked)
            {
                switch (m_cboNumberScheme.SelectedIndex)
                {
                case 0: bulInfo.m_numberScheme = VwBulNum.kvbnArabic; break;

                case 1: bulInfo.m_numberScheme = VwBulNum.kvbnRomanUpper; break;

                case 2: bulInfo.m_numberScheme = VwBulNum.kvbnRomanLower; break;

                case 3: bulInfo.m_numberScheme = VwBulNum.kvbnLetterUpper; break;

                case 4: bulInfo.m_numberScheme = VwBulNum.kvbnLetterLower; break;

                case 5: bulInfo.m_numberScheme = VwBulNum.kvbnArabic01; break;
                }
                bulInfo.m_start      = m_nudStartAt.Value;
                bulInfo.m_textBefore = m_tbTextBefore.Text;
                bulInfo.m_textAfter  = m_tbTextAfter.Text;
                bulInfo.FontInfo     = m_NumberFontInfo;
            }
        }
Пример #13
0
    //タイマー更新。
    private void SetDisplayGUI()
    {
        //残り時間を取得。
        float time = _LineInfo.timer;

        //タイマー更新。
        if (time >= 0)
        {
            float max = _TakeTime * 60.0f;
            //ゲージ更新。
            _Gauge.fillAmount = Mathf.Max(0.0f, 1.0f - (time / max));

            _DisplayText.text = (time == 0) ? "完成" : String.Format("{0:00}:{1:00}", Mathf.Floor(time / 60), (time % 60));
        }
        else
        {
            //ゲージ更新。
            _Gauge.fillAmount = 0.0f;
            BulletInfo info = recipe.bulletInfo;
            if (info != null)
            {
                //情報表示。
                _DisplayText.text = string.Format("名前:{0}\n" +
                                                  "生産コスト:{1}\n" +
                                                  "生産個数:{2:####}", info.Name, recipe.cost, recipe.generateNum);
            }
            else
            {
                //情報表示。
                _DisplayText.text = "レシピが設定されていません。";
            }
        }
    }
Пример #14
0
        public void RoundTripEncodingAndDecodingOfFontInfo()
        {
            // Setup what we expect
            FontInfo expectedFontInfo = m_infoTable["TestStyle"].FontInfoForWs(-1);

            expectedFontInfo.m_fontName       = new InheritableStyleProp <string>("Algerian");
            expectedFontInfo.m_fontSize       = new InheritableStyleProp <int>(8000);
            expectedFontInfo.m_fontColor      = new InheritableStyleProp <Color>(Color.Red);
            expectedFontInfo.m_backColor      = new InheritableStyleProp <Color>(Color.White);
            expectedFontInfo.m_underline      = new InheritableStyleProp <FwUnderlineType>(FwUnderlineType.kuntNone);
            expectedFontInfo.m_underlineColor = new InheritableStyleProp <Color>(Color.Black);
            expectedFontInfo.m_bold           = new InheritableStyleProp <bool>(false);
            expectedFontInfo.m_italic         = new InheritableStyleProp <bool>(false);
            expectedFontInfo.m_superSub       = new InheritableStyleProp <FwSuperscriptVal>(FwSuperscriptVal.kssvOff);
            expectedFontInfo.m_offset         = new InheritableStyleProp <int>(0);

            BulletInfo bulletInfo1 = new BulletInfo();

            bulletInfo1.FontInfo = expectedFontInfo;

            BulletInfo bulletInfo2 = new BulletInfo();

            bulletInfo2.EncodedFontInfo = bulletInfo1.EncodedFontInfo;

            Assert.AreEqual(expectedFontInfo, bulletInfo2.FontInfo);
        }
Пример #15
0
            public static object DeserializeBulletInfo(byte[] bytes)
            {
                Vector3      startPos  = Vector3.zero;
                Vector3      direction = Vector3.zero;
                PhotonPlayer shooter   = PhotonNetwork.player;
                int          shooterID = 0;
                Vector3      speed     = Vector3.zero;
                int          id        = 0;

                int index = 0;

                ExitGames.Client.Photon.Protocol.Deserialize(out startPos.x, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out startPos.y, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out startPos.z, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out direction.x, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out direction.y, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out direction.z, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out shooterID, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out speed.x, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out speed.y, bytes, ref index);
                ExitGames.Client.Photon.Protocol.Deserialize(out speed.z, bytes, ref index);

                ExitGames.Client.Photon.Protocol.Deserialize(out id, bytes, ref index);

                shooter = shooter.Get(shooterID);

                BulletInfo bulletInfo = new BulletInfo(startPos, direction, shooter, speed, id);

                return(bulletInfo);
            }
Пример #16
0
 public static void CreateBullet(BulletInfo bullet, Vector3 position)
 {
     if (bullet != null)
     {
         if (bullet.GetType() == Bullet.NORMAL_BULLET)
         {
             Instantiate(instance.normalBullet, position, Quaternion.identity);
         }
         if (bullet.GetType() == Bullet.FIRE_BULLET)
         {
             Instantiate(instance.fireBullet, position, Quaternion.identity);
         }
         if (bullet.GetType() == Bullet.ICE_BULLET)
         {
             Instantiate(instance.iceBullet, position, Quaternion.identity);
         }
         if (bullet.GetType() == Bullet.IEM_BULLET)
         {
             Instantiate(instance.iemBullet, position, Quaternion.identity);
         }
         if (bullet.GetType() == Bullet.WIND_BULLET)
         {
             Instantiate(instance.windBullet, position, Quaternion.identity);
         }
         if (bullet.GetType() == Bullet.BOMB_BULLET)
         {
             GameObject bomb = Instantiate(DestroyableUtils.GetBomb(), position, Quaternion.Euler(-90, 0, 0));
             bomb.GetComponent <Bomb>().SetBoat(bullet.GetBoat());
             bomb.GetComponent <Bomb>().SetIsShootable(true);
         }
     }
 }
Пример #17
0
    public BulletInfo RayShoot()
    {
        BulletInfo bulletInfo = new BulletInfo();
        Ray        ray        = new Ray(transform.position, transform.forward);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            // 如果射线与平面碰撞,打印碰撞物体信息
            Debug.Log("碰撞对象: " + hit.collider.name);
            // 在场景视图中绘制射线
            Debug.DrawLine(ray.origin, hit.point, Color.red);
            GameObject obj = hit.transform.gameObject;

            switch (obj.tag)
            {
            case nameof(Tag.Box):
                Box box = obj.GetComponent <Box>();
                bulletInfo.shootTag  = ShootTag.Box;
                bulletInfo.shootInfo = box.myInfo.myIndex + "";
                break;

            case nameof(Tag.Member):
                CharacterCommon member = obj.GetComponent <CharacterCommon>();
                bulletInfo.shootTag  = ShootTag.Character;
                bulletInfo.shootInfo = member.myIndex + "";
                break;

            default:    //墙体及障碍物
                bulletInfo.shootTag = ShootTag.Wall;
                break;
            }
        }
        return(null);
    }
Пример #18
0
 /// <summary>
 /// 子弹射中谁
 /// </summary>
 /// <param name="bulletInfo"></param>
 public void SendNetInfo(BulletInfo bulletInfo)
 {
     //发送
     byte[] message = SerializeHelper.Serialize <BulletInfo>(bulletInfo);
     //SocketManager.instance.SendSave((byte)MessageConvention.bulletInfo, message, false);
     UDPManager.instance.SendSave((byte)MessageConvention.bulletInfo, message);
 }
Пример #19
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the <see cref="FwBulletsTab"/> class.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public FwBulletsTab()
 {
     InitializeComponent();
     m_currentStyleBulletInfo = new BulletInfo();
     UpdateGroupBoxes();
     m_cboBulletScheme.SelectedIndex = m_kDefaultBulletIndex;
     m_cboNumberScheme.SelectedIndex = m_kDefaultNumberIndex;
 }
Пример #20
0
    public virtual void SetDirection(BulletInfo dir)
    {
        Debug.Log("this is SetDirection");

        direction = dir.direction;
        StartCoroutine("DestroyBullet", dir.timeLive);
        rigidBody2D.velocity = direction * maxSpeed;
    }
Пример #21
0
 private static void OnBulletHit(UseableGun useableGun, BulletInfo bulletInfo, InputInfo hit,
                                 ref bool shouldAllow)
 {
     if (hit.player)
     {
         Accuracies[useableGun.player.channel.owner].ShotsHit++;
     }
 }
Пример #22
0
 // ------------------------------------------------------------------
 // Desc:
 // ------------------------------------------------------------------
 public void Init( BulletInfo _info )
 {
     type = _info.type;
     maxDuration = _info.maxDuration;
     reps = _info.reps;
     speed = _info.speed;
     startTime = _info.startTime;
 }
Пример #23
0
 public void ButtleHit(BulletInfo info)
 {
     hp -= info.damanage;
     if (hp <= 0)
     {
         Destroy(gameObject);
     }
 }
Пример #24
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="T:FwBulletsTab"/> class.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public FwBulletsTab()
		{
			InitializeComponent();
			m_currentStyleBulletInfo = new BulletInfo();
			UpdateGroupBoxes();
			m_cboBulletScheme.SelectedIndex = m_kDefaultBulletIndex;
			m_cboNumberScheme.SelectedIndex = m_kDefaultNumberIndex;
		}
Пример #25
0
    protected virtual void FireProjectile(Vector3 targetPos)
    {
        bullet = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
        BulletInfo bulletinfo = bullet.GetComponent <BulletInfo>();

        bulletinfo.setSpeed     = projectileSpeed;
        bulletinfo.setTargetPos = targetPos;
        bulletinfo.setDamage    = damage;
    }
Пример #26
0
        //Calculate bullet drop to a point
        //BUG: Drop will be more innacurate the higher the slope to target
        //Rotation in the math maybe??
        public float DropCalc(Vector3 point)
        {
            float treturn = 0f;

            if (Vector3.Distance(point, Player.player.look.aim.position) < 5f)
            {
                return(0f);
            }

            ItemGunAsset firearm = (ItemGunAsset)Player.player.equipment.asset;

            Quaternion quaternion    = Quaternion.LookRotation(point - Player.player.look.transform.position, Player.player.look.transform.up);
            Vector3    targetForward = quaternion * Vector3.forward;

            BulletInfo bulletInfo = new BulletInfo();

            bulletInfo.pos = Player.player.look.transform.position;
            bulletInfo.dir = targetForward.normalized;

            float num = firearm.ballisticDrop;

            bulletInfo.barrelAsset = Player.player.equipment.thirdModel.gameObject.GetComponent <Attachments>().barrelAsset;
            if (bulletInfo.barrelAsset != null)
            {
                num *= bulletInfo.barrelAsset.ballisticDrop;
            }

            int ticker = 0;

            while (++ticker < firearm.ballisticSteps)
            {
                bulletInfo.pos   += bulletInfo.dir * firearm.ballisticTravel;
                bulletInfo.dir.y -= num;
                bulletInfo.dir.Normalize();

                if (Vector3.Distance(
                        new Vector3(point.x, 0f, point.z),
                        new Vector3(bulletInfo.pos.x, 0f, bulletInfo.pos.z))
                    < firearm.ballisticTravel
                    )
                {
                    treturn = bulletInfo.pos.y - point.y;
                    break;
                }
            }

            if (treturn < 0)
            {
                treturn -= treturn * 2;
            }
            else
            {
                treturn = 0f;
            }

            return(treturn);
        }
Пример #27
0
 void OnEnable()
 {
     info = new BulletInfo(transform.up, timeLiveBullet);
     if (!useMasterPistol)
     {
         StopCoroutine("Shoot");
         StartCoroutine("Shoot", TimeToFirstShoot);
     }
 }
Пример #28
0
 public void setBulletInfo(BulletInfo info)
 {
     this.bulletInfo = info;
     if (this.bulletInfo != null)
     {
         initBullet();
     }
     isInit = true;
 }
Пример #29
0
    //添加子弹
    public BulletInfo AddBullet(int effectId, CharacterInfo charInfo, CharacterInfo targetInfo, float speed, int triggerGroupId = 0)
    {
        bulletIndexId += 1;
        BulletInfo effectInfo = new BulletInfo(bulletIndexId, effectId, charInfo, targetInfo, speed, triggerGroupId);

        bullets.Add(bulletIndexId, effectInfo);
        this.eventDispatcher.Broadcast("AddBullet", effectInfo);
        return(effectInfo);
    }
 public bool IsMatched(BulletInfo bulletInfo)
 {
     return(CmdSeq == bulletInfo.CmdSeq &&
            StartPoint == bulletInfo.StartPoint &&
            EmitPoint == bulletInfo.EmitPoint &&
            StartDir == bulletInfo.StartDir &&
            HitPoint == bulletInfo.HitPoint &&
            HitType == bulletInfo.HitType);
 }
Пример #31
0
 public static PlayerShoot Read(NetIncomingMessage msg)
 {
     return(new PlayerShoot
     {
         playerId = msg.ReadByte(),
         from = msg.ReadVector3(),
         bullets = BulletInfo.ReadAll(msg)
     });
 }
Пример #32
0
    public void SetBulletInfo(BulletInfo info)
    {
        //
        int boxIndex = int.Parse(info.shootInfo);
        Box box      = allBox[boxIndex];

        //
        box.BeShot();
    }
Пример #33
0
    private void Start()
    {
        BulletInfo info = Bullets[DEFAULT_BULLET].GetComponent <BulletInfo>();

        Speed    = info.Speed;
        Cooldown = info.Cooldown;

        _aimindic = gameObject.transform.Find("Canvas").Find("AimIndicator").GetComponent <SpriteRenderer>();
    }
Пример #34
0
    public void OnPointerEnter(PointerEventData eventData)
    {
        BulletInfo info = Data.GetBulletInfo(Data.Deck.bullets[idx]);

        if (info != null)
        {
            _DescriptionText.text = info.Name;
        }
    }
    // Use this for initialization
    void Start()
    {
        bulInfo = gameObject.GetComponent<BulletInfo>();

        Collider2D[] hits = Physics2D.OverlapCircleAll (gameObject.transform.position, WorldGenerator.worldspec.cellLength, mask, -5, 5);

        if(hits.Length > 0)
        {
            bulInfo.target = hits[Random.Range(0, hits.Length - 1)].gameObject;
        }
    }
Пример #36
0
        public Bullet(BulletInfo info, ProjectileArgs args)
        {
            this.info = info;
            this.args = args;
            pos = args.Source;

            var world = args.SourceActor.World;

            if (info.LaunchAngle.Length > 1)
                angle = new WAngle(world.SharedRandom.Next(info.LaunchAngle[0].Angle, info.LaunchAngle[1].Angle));
            else
                angle = info.LaunchAngle[0];

            if (info.Speed.Length > 1)
                speed = new WDist(world.SharedRandom.Next(info.Speed[0].Length, info.Speed[1].Length));
            else
                speed = info.Speed[0];

            target = args.PassiveTarget;
            if (info.Inaccuracy.Length > 0)
            {
                var inaccuracy = Util.ApplyPercentageModifiers(info.Inaccuracy.Length, args.InaccuracyModifiers);
                var range = Util.ApplyPercentageModifiers(args.Weapon.Range.Length, args.RangeModifiers);
                var maxOffset = inaccuracy * (target - pos).Length / range;
                target += WVec.FromPDF(world.SharedRandom, 2) * maxOffset / 1024;
            }

            facing = (target - pos).Yaw.Facing;
            length = Math.Max((target - pos).Length / speed.Length, 1);

            if (!string.IsNullOrEmpty(info.Image))
            {
                anim = new Animation(world, info.Image, new Func<int>(GetEffectiveFacing));
                anim.PlayRepeating(info.Sequences.Random(world.SharedRandom));
            }

            if (info.ContrailLength > 0)
            {
                var color = info.ContrailUsePlayerColor ? ContrailRenderable.ChooseColor(args.SourceActor) : info.ContrailColor;
                contrail = new ContrailRenderable(world, color, info.ContrailWidth, info.ContrailLength, info.ContrailDelay, info.ContrailZOffset);
            }

            trailPalette = info.TrailPalette;
            if (info.TrailUsePlayerPalette)
                trailPalette += args.SourceActor.Owner.InternalName;

            smokeTicks = info.TrailDelay;
        }
Пример #37
0
        public Bullet(BulletInfo info, ProjectileArgs args)
        {
            Info = info;
            Args = args;

            if (info.Inaccuracy > 0)
            {
                var factor = ((Args.dest - Args.src).Length / Game.CellSize) / args.weapon.Range;
                Args.dest += (info.Inaccuracy * factor * args.firedBy.World.SharedRandom.Gauss2D(2)).ToInt2();
            }

            if (Info.Image != null)
            {
                anim = new Animation(Info.Image, GetEffectiveFacing);
                anim.PlayRepeating("idle");
            }
        }
Пример #38
0
    void FireGun()
    {
        // Shoot a ray from the center of the screen and send a message to any object hit
        Ray ray = Camera.main.ViewportPointToRay (new Vector3 (0.5f,0.5f,0.0f));
        RaycastHit info;
        BulletInfo bulletInfo = new BulletInfo();
        if (Physics.Raycast (ray, out info)) {
            bulletInfo.hitInfo = info;
            bulletInfo.ray = ray;
            bulletInfo.force = bulletForce;
            info.collider.SendMessageUpwards ("WasShot", bulletInfo, SendMessageOptions.DontRequireReceiver);

            MakeIonTrail2 (ray.origin,info.point);
        }

        // Play gun shot sound effect
        audioSource.PlayOneShot(audioSource.clip);
    }
Пример #39
0
        public Bullet(BulletInfo info, ProjectileArgs args)
        {
            this.info = info;
            this.args = args;
            this.pos = args.Source;

            var world = args.SourceActor.World;

            if (info.Angle.Length > 1 && info.Speed.Length > 1)
            {
                angle = new WAngle(world.SharedRandom.Next(info.Angle[0].Angle, info.Angle[1].Angle));
                speed = new WRange(world.SharedRandom.Next(info.Speed[0].Range, info.Speed[1].Range));
            }
            else
            {
                angle = info.Angle[0];
                speed = info.Speed[0];
            }

            target = args.PassiveTarget;
            if (info.Inaccuracy.Range > 0)
            {
                var inaccuracy = OpenRA.Traits.Util.ApplyPercentageModifiers(info.Inaccuracy.Range, args.InaccuracyModifiers);
                var maxOffset = inaccuracy * (target - pos).Length / args.Weapon.Range.Range;
                target += WVec.FromPDF(world.SharedRandom, 2) * maxOffset / 1024;
            }

            facing = OpenRA.Traits.Util.GetFacing(target - pos, 0);
            length = Math.Max((target - pos).Length / speed.Range, 1);

            if (info.Image != null)
            {
                anim = new Animation(world, info.Image, GetEffectiveFacing);
                anim.PlayRepeating("idle");
            }

            if (info.ContrailLength > 0)
            {
                var color = info.ContrailUsePlayerColor ? ContrailRenderable.ChooseColor(args.SourceActor) : info.ContrailColor;
                trail = new ContrailRenderable(world, color, info.ContrailLength, info.ContrailDelay, 0);
            }

            smokeTicks = info.TrailDelay;
        }
Пример #40
0
        public Bullet(BulletInfo info, ProjectileArgs args)
        {
            this.info = info;
            this.args = args;
            this.pos = args.Source;

            // Convert ProjectileArg definitions to world coordinates
            // TODO: Change the yaml definitions so we don't need this
            var range = new WRange((int)(1024 * args.Weapon.Range)); // Range in world units
            var inaccuracy = new WRange((int)(info.Inaccuracy * 1024 / Game.CellSize)); // Offset in world units at max range
            var speed = (int)(info.Speed * 4 * 1024 / (10 * Game.CellSize)); // Speed in world units per tick
            angle = WAngle.ArcTan((int)(info.Angle * 4 * 1024), 1024); // Angle in world angle

            target = args.PassiveTarget;
            if (info.Inaccuracy > 0)
            {
                var maxOffset = inaccuracy.Range * (target - pos).Length / range.Range;
                target += WVec.FromPDF(args.SourceActor.World.SharedRandom, 2) * maxOffset / 1024;
            }

            facing = Traits.Util.GetFacing(target - pos, 0);
            length = Math.Max((target - pos).Length / speed, 1);

            if (info.Image != null)
            {
                anim = new Animation(info.Image, GetEffectiveFacing);
                anim.PlayRepeating("idle");
            }

            if (info.ContrailLength > 0)
            {
                var color = info.ContrailUsePlayerColor ? ContrailRenderable.ChooseColor(args.SourceActor) : info.ContrailColor;
                trail = new ContrailRenderable(args.SourceActor.World, color, info.ContrailLength, info.ContrailDelay, 0);
            }

            smokeTicks = info.TrailDelay;
        }
		public void AddBullet(BulletInfo n)
		{
            Bullets.Add(n);


			var p = default(Point);

			var c = 0;

			n.Element.PositionChanged +=
				delegate
				{
					c++;

					var k = n.Element.ToPoint();

					var DoHitTest = ((k - p).length > 12);

					if (c % 4 == 0)
						DoHitTest = true;

					if (DoHitTest)
					{
						// only check for hit on each moved one pixel

						BulletHitTest(n);
					}

					p = k;
				};

			n.Element.removed +=
				delegate
				{
					Bullets.Remove(n);
				};
		}
Пример #42
0
        public Bullet(BulletInfo info, ProjectileArgs args)
        {
            Info = info;
            Args = args;

            if (info.Inaccuracy > 0)
            {
                var factor = ((Args.dest - Args.src).Length / Game.CellSize) / args.weapon.Range;
                Args.dest += (info.Inaccuracy * factor * args.firedBy.World.SharedRandom.Gauss2D(2)).ToInt2();
            }

            if (Info.Image != null)
            {
                anim = new Animation(Info.Image, GetEffectiveFacing);
                anim.PlayRepeating("idle");
            }

            if (Info.ContrailLength > 0)
            {
                Trail = new ContrailHistory(Info.ContrailLength,
                    Info.ContrailUsePlayerColor ? ContrailHistory.ChooseColor(args.firedBy) : Info.ContrailColor,
                    Info.ContrailDelay);
            }
        }
 public void SetCurrentBulletInfo(BulletInfo bullet)
 {
     bulInfo = bullet;
     fireTimer = resetTime = bulInfo.fireRate;
 }
Пример #44
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Updates the form based on a style being selected.
		/// </summary>
		/// <param name="styleInfo">The style info.</param>
		/// ------------------------------------------------------------------------------------
		public void UpdateForStyle(StyleInfo styleInfo)
		{
			CheckDisposed();
			m_dontUpdateInheritance = true;

			bool fDifferentStyle = m_StyleInfo == null ? true : (styleInfo.Name != m_StyleInfo.Name);

			m_StyleInfo = styleInfo;
			m_preview.IsRightToLeft = m_StyleInfo.DirectionIsRightToLeft == TriStateBool.triNotSet ?
				m_DefaultTextDirectionRtoL : m_StyleInfo.DirectionIsRightToLeft == TriStateBool.triTrue;
			m_preview.WritingSystemFactory = m_StyleInfo.Cache.LanguageWritingSystemFactoryAccessor;
			m_preview.WritingSystemCode = m_StyleInfo.Cache.DefaultVernWs;

			VwBulNum bulletType;
			// Note: don't assign m_currentStyleBulletInfo until the end of this method
			// since setting some of the values change m_currentStyleBulletInfo before we have set
			// everything.
			BulletInfo bulletInfo = new BulletInfo(styleInfo.IBullet.Value);
			bulletType = bulletInfo.m_numberScheme;

			// If we have a different style, we have to reload the font info. If it is the same
			// style we were here before so we keep the font info that we already have.
			if (fDifferentStyle)
			{
				if ((int)bulletType >= (int)VwBulNum.kvbnBulletBase)
				{
					// use font from style for bullets
					m_BulletsFontInfo = bulletInfo.FontInfo;
					// create a number font based on the font for bullets
					m_NumberFontInfo = new FontInfo(m_BulletsFontInfo);
					m_NumberFontInfo.m_fontName.ResetToInherited(GetUiFontName(
						styleInfo.FontInfoForWs(-1).m_fontName.Value));
				}
				else
				{
					// use font from style for numbers
					m_NumberFontInfo = bulletInfo.FontInfo;

					if (bulletType == VwBulNum.kvbnNone)
					{
						m_NumberFontInfo.m_fontName.ResetToInherited(GetUiFontName(
							styleInfo.FontInfoForWs(-1).m_fontName.Value));
					}

					// create a bullets font based on the font for numbers
					m_BulletsFontInfo = new FontInfo(m_NumberFontInfo);

					// The font for bullets is hard-coded in the views code, so there is no point
					// in letting the user select any other font for bullets.
					m_BulletsFontInfo.m_fontName.ResetToInherited("Wingdings");
					m_BulletsFontInfo.m_fontName.SetDefaultValue("Wingdings");
				}
			}

			m_nudStartAt.Value = bulletInfo.m_start;
			m_chkStartAt.Checked = (bulletInfo.m_start != 1);

			m_tbTextBefore.Text = bulletInfo.m_textBefore;
			m_tbTextAfter.Text = bulletInfo.m_textAfter;

			m_rbUnspecified.Enabled = styleInfo.Inherits;
			if (styleInfo.IBullet.IsInherited && styleInfo.Inherits)
				m_rbUnspecified.Checked = true;
			else if (bulletType == VwBulNum.kvbnNone)
				m_rbNone.Checked = true;
			else if ((int)bulletType >= (int)VwBulNum.kvbnBulletBase)
				m_rbBullet.Checked = true;
			else // NumberBase
				m_rbNumber.Checked = true;

			m_cboBulletScheme.SelectedIndex = GetBulletIndexForType(bulletType);
			m_cboNumberScheme.SelectedIndex = GetNumberSchemeIndexForType(bulletType);

			m_currentStyleBulletInfo = bulletInfo;
			UpdateBulletSchemeComboBox();

			m_dontUpdateInheritance = false;
		}
    // Update is called once per frame
    void Update()
    {
        if(fireTimer > 0)
        {
            fireTimer -= Time.deltaTime;
        }

        if(Joystick.RightStick.GetMagnitude() >= 0.5f && fireTimer <= 0)
        {
            if(currentBullets && WeaponManager.Instance.CurrentAmmo > 0)
            {
                if(WeaponManager.Instance.ammo != WeaponManager.ammoType.beam)
                {
                    bulInfo.travelAngle = Joystick.RightStick.GetAngle();
                    GameObject.Instantiate(currentBullets, weaponAnchor.position, Quaternion.identity);
                    WeaponManager.Instance.ConsumeAmmo(bulInfo.cost);
                }
                else if(WeaponManager.Instance.ammo == WeaponManager.ammoType.beam)
                {
                    float angle = Joystick.RightStick.GetAngle();
                    if(!hasSpawned)
                    {
                        bulInfo.travelAngle = Joystick.RightStick.GetAngle();
                        spawnedObject = GameObject.Instantiate(currentBullets, weaponAnchor.position, Quaternion.identity) as GameObject;
                        spawnedBulInfo = spawnedObject.GetComponent<BulletInfo>();
                        hasSpawned = true;
                    }
                    else
                    {
                        spawnedObject.transform.rotation = Quaternion.AngleAxis(angle, new Vector3(0f,0f,1.0f));
                        spawnedBulInfo.travelAngle = Joystick.RightStick.GetAngle();
                    }
                    WeaponManager.Instance.ConsumeAmmo(bulInfo.cost * Time.deltaTime);
                }

                fireTimer = resetTime;
            }
        }
        else if(Joystick.RightStick.GetMagnitude() < 0.5f && hasSpawned)
        {
            Destroy(spawnedObject);
            hasSpawned = false;
        }
    }
Пример #46
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Saves bullet info into a StyleInfo
		/// </summary>
		/// <param name="styleInfo">styleInfo to save into</param>
		/// ------------------------------------------------------------------------------------
		public void SaveToInfo(StyleInfo styleInfo)
		{
			CheckDisposed();

			// Save the bullet information
			styleInfo.IBullet.IsInherited = false;
			BulletInfo bulInfo = new BulletInfo();
			UpdateBulletInfo(ref bulInfo);

			// Replace the value
			if (styleInfo.IBullet.Save(m_rbUnspecified.Checked, bulInfo))
				styleInfo.Dirty = true;
		}
Пример #47
0
        public Game()
            : base(DefaultWidth, DefaultHeight)
        {
            InitializeRoutedActions();
            InitializeSharedState();

            SoundEnabled = true;

            Action<Sound> play =
                s =>
                {
                    if (CanvasOverlay.parent == null)
                        return;

                    if (SoundEnabled)
                        s.play();
                };

            var Menu = new MenuSprite(DefaultWidth).AttachTo(base.InfoOverlay);

            Menu.TextExternalLink2.htmlText = LinkPlayMoreGames;

            var DefenseY = 420;

            #region DebugDump
            var DebugDump = new DebugDumpTextField();

            DebugDump.Field.y = DefaultHeight / 4;
            DebugDump.Field.x = 0;

            DebugDump.Field.width = DefaultWidth;
            DebugDump.Field.height = DefaultHeight / 2;

            DebugDump.Visible.ValueChangedToTrue +=
                delegate
                {
                    Menu.TextExternalLink2.htmlText = LinkPoweredByJSC;
                    DebugDump.Field.AttachToBefore(BorderOverlay);
                    DebugDump.DebugDumpUpdate();
                };

            DebugDump.Visible.ValueChangedToFalse +=
                delegate
                {
                    Menu.TextExternalLink2.htmlText = LinkPlayMoreGames;
                };
            #endregion

            RoutedActions.SendTextMessage.Direct =
                e => DebugDump.Write(new { Message = e });

            this.Statusbar = new Statusbar();

            Statusbar.Lives.Value = 3;
            Statusbar.Score.Value = 0;

            Statusbar.Element.AttachTo(InfoOverlay);

            var MenuFader = new DualFader { Value = Menu };



            #region common keys
            this.InvokeWhenStageIsReady(
                delegate
                {
                    stage.click +=
                        delegate
                        {
                            if (MenuFader.Value != CanvasOverlay)
                                MenuFader.Value = CanvasOverlay;
                        };


                    stage.keyUp +=
                        e =>
                        {
                            if (e.keyCode == Keyboard.ENTER)
                            {
                                MenuFader.Value = CanvasOverlay;
                            }

                            if (e.keyCode == Keyboard.ESCAPE)
                            {
                                MenuFader.Value = Menu;
                            }

                            if (e.keyCode == Keyboard.T)
                            {
                                DebugDump.Visible.Toggle();

                            }

                            if (e.keyCode == Keyboard.M)
                            {
                                SoundEnabled = !SoundEnabled;

                            }

                            if (e.keyCode == Keyboard.C)
                            {
                                play(Sounds.miu);

                                foreach (var v in cloud1.Members)
                                {
                                    DebugDump.Write(new { v.Element.x, v.Element.y });
                                }

                                DebugDump.Write(new { PlaysSurvived = this.PlaysSurvived.Value });

                            }
                        };
                }
            );

            #endregion






            this.Ego = new PlayerShip(DefaultWidth, DefaultHeight)
                {
                    Name = "Ego"
                };

            // addding our entities to list ensures we know under what id to send them
            this.Ego.AddTo(this.SharedState.LocalObjects);
            this.Ego.GoodEgo.AddTo(this.SharedState.LocalObjects);
            this.Ego.EvilEgo.AddTo(this.SharedState.LocalObjects);

            // our ego cannot be hit while the menu is showing
            this.Ego.GodMode.ValueChangedTo +=
                GodMode => DebugDump.Write(new { GodMode });

            // MenuFader.ValueChangedTo += e => this.Ego.GodMode.Value = e == Menu;
            // this.Ego.GodMode.Value = true;



            var ReportedScore = 0;

            #region lives and gameover

            Action<StarShip> ApplyEgoRespawn =
                xego =>
                {
                    var WaitingForRespawn = false;

                    xego.IsAlive.ValueChangedToFalse +=
                        delegate
                        {
                            if (WaitingForRespawn)
                                return;

                            WaitingForRespawn = true;

                            this.ApplyFilter(Filters.GrayScaleFilter);
                            this.RoutedActions.SendTextMessage.Direct("waiting for respawn...");

                            if (PlayerInput != null)
                                PlayerInput.Enabled.Value = false;

                            Statusbar.Lives.Value--;

                            if (Statusbar.Lives <= 0)
                            {
                                var ScoreMinStep = this.Statusbar.Score.Value / 30;

                                100.AtInterval(
                                    t =>
                                    {
                                        var v = Math.Max((this.Statusbar.Score.Value - ScoreMinStep),0);

                                        Statusbar.Score.Value = v;

                                        if (v == 0)
                                            t.stop();
                                    }
                                );
                            }

                            3100.AtDelayDo(
                                delegate
                                {
                                    this.RoutedActions.SendTextMessage.Direct("respawn!");


                                    if (Statusbar.Lives == 0)
                                    {
                                        Statusbar.Lives.Value = 3;
                                        Statusbar.Score.Value = 0;
                                        PlaysSurvived.Value = 0;
                                    }



                                    if (Statusbar.Score.Value > 0)
                                    {
                                        this.RoutedActions.AddRankingScore.Chained(Statusbar.Score.Value - ReportedScore);

                                        ReportedScore = Statusbar.Score.Value;
                                    }

                                    WaitingForRespawn = false;

                                    this.RoutedActions.RestoreStarship.Chained(xego);

                                    this.filters = null;

                                    if (PlayerInput != null)
                                        PlayerInput.Enabled.Value = true;

                                    play(Sounds.insertcoin);
                                }
                            );

                        };
                };


            ApplyEgoRespawn(this.Ego.GoodEgo);
            ApplyEgoRespawn(this.Ego.EvilEgo);

            #endregion


            #region input
            RoutedActions.DoPlayerMovement.Direct +=
                (e, p) =>
                {
                    e.GoodEgo.MoveToTarget.Value = p;
                };

            Action<double, double> DoEgoPlayerMovement =
                (arc, length) =>
                     RoutedActions.DoPlayerMovement.Chained(Ego, Ego.GoodEgo.ToPoint().MoveToArc(arc, Ego.GoodEgo.MaxStep * length));

            this.RoutedActions.RestoreStarship.Direct =
                s =>
                {
                    DebugDump.Write("restore starship: " + s.Name);


                    s.GodMode.Value = true;
                    s.TakeDamage(0);
                    s.ApplyFilter(new BlurFilter());
                    s.alpha = 1;

                    2000.AtDelayDo(
                        delegate
                        {
                            s.GodMode.Value = false;
                            s.filters = null;

                            if (this.CoPlayers.Any(k => s == k.GoodEgo))
                                s.ApplyFilter(Filters.ColorFillFilter(0xff));
                        }
                    );
                };

            this.InvokeWhenStageIsReady(
                delegate
                {

                    PlayerInput = new PlayerInput(stage, Ego, this)
                    {
                        StepLeft = () => DoEgoPlayerMovement(Math.PI, 2),
                        StepLeftEnd = () => DoEgoPlayerMovement(Math.PI, 0.5),

                        StepRight = () => DoEgoPlayerMovement(0, 2),
                        StepRightEnd = () => DoEgoPlayerMovement(0, 0.5),

                        FireBullet = () => Ego.FireBullet(),

                        SmartMoveTo = (x, y) =>
                            {
                                // ignore mouse while out of bounds
                                if (x < 0)
                                    return;

                                if (x > DefaultWidth)
                                    return;

                                RoutedActions.DoPlayerMovement.Chained(Ego, new Point(Ego.Wrapper(x, y), Ego.GoodEgoY));

                            }

                    };

                    PlayerInput.Enabled.ValueChangedTo +=
                        InputEnabled =>
                        {
                            DebugDump.Write(new { InputEnabled });

                        };


                }
            );
            #endregion

            this.GroupEnemies.Add(this.Ego.EvilEgo);

            // hide menu for fast start
            // MenuFader.Value = CanvasOverlay;

            this.PlaysSurvived.ValueChangedTo +=
                PlaysSurvived => DebugDump.Write(new { PlaysSurvived });

            this.PlaysSurvived.ValueChangedTo +=
                PlaysSurvived =>
                {
                    if (PlaysSurvived == 5)
                        this.RoutedActions.AddAchivementFiver.ChainedOnce();

                    if (PlaysSurvived == 1)
                        this.RoutedActions.AddAchivementFirst.ChainedOnce();
                };


            const int ClipMargin = 20;

            #region evilmode

            this.Ego.EvilMode.ValueChangedToTrue +=
                delegate
                {
                    play(Sounds.fade);

                    #region keep ego here for 10 secs

                    this.Ego.GoodEgo.Clip =
                        p =>
                        {
                            if (p.x < DefaultWidth / 2)
                            {
                                p.x = Math.Min(p.x, -ClipMargin);
                            }
                            else
                            {
                                p.x = Math.Max(p.x, DefaultWidth + ClipMargin);
                            }

                            return p;
                        };

                    5000.AtDelayDo(
                        delegate
                        {
                            this.Ego.GoodEgo.Clip = null;
                            play(Sounds.fade);
                        }
                    );
                    #endregion

                };

            this.Ego.EvilMode.ValueChangedToFalse +=
                delegate
                {
                    play(Sounds.insertcoin);
                };

            #endregion

            this.Ego.EvilMode.LinkTo(Statusbar.EvilMode);

            #region evilmode indicator
            this.Ego.EvilMode.ValueChangedToTrue +=
                delegate
                {
                    this.filters = new[] { Filters.RedChannelFilter };
                };

            this.Ego.EvilMode.ValueChangedToFalse +=
                delegate
                {
                    this.filters = null;
                };
            #endregion

            this.Ego.GoodEgo.FireBullet = RoutedActions.FireBullet;
            this.Ego.GoodEgo.AttachTo(CanvasOverlay);

            this.Ego.EvilEgo.FireBullet = RoutedActions.FireBullet;
            this.Ego.EvilEgo.AttachTo(CanvasOverlay);

            #region  build shared defense buildings
            for (int i = 0; i < 4; i++)
            {
                var offset = DefaultWidth * (i * 2 + 1) / 8;


                foreach (var v in DefenseBlock.CreateDefenseArray(offset, DefenseY))
                {
                    v.AttachTo(CanvasOverlay);
                    v.AddTo(DefenseBlocks);
                    v.AddTo(FragileEntities.Items);

                    // defense blocks like invaders cloud are shared
                    this.SharedState.SharedObjects.Add(v);
                }
            }
            #endregion


            Ego.AddTo(FragileEntities);

            #region Create and Move CoPlayer

            RoutedActions.CreateCoPlayer.Direct =
                (user, handler) =>
                {
                    var cp1 = new PlayerShip(DefaultWidth, DefaultHeight)
                        {
                            Name = "CoPlayer"
                        }.AddTo(CoPlayers);

                    cp1.GoodEgo.AttachTo(CanvasOverlay);
                    cp1.EvilEgo.AttachTo(CanvasOverlay);

                    // we are adding remote controlled objects
                    cp1.AddTo(this.SharedState.RemoteObjects[user]);

                    cp1.GoodEgo.AddTo(this.SharedState.RemoteObjects[user]);
                    cp1.EvilEgo.AddTo(this.SharedState.RemoteObjects[user]);

                    // group as enemies
                    cp1.EvilEgo.AddTo(this.GroupEnemies);
                    cp1.GoodEgo.ApplyFilter(Filters.ColorFillFilter(0xff));
                    cp1.AddTo(FragileEntities);

                    handler(cp1);

                    // this entity only moves when that player wants to move...

                    // yet we might need to notify of damage
                };

            RoutedActions.RemoveCoPlayer.Direct =
                user =>
                {
                    var CoPlayer = (PlayerShip)this.SharedState.RemoteObjects[user][0];

                    this.SharedState.RemoteObjects[user].Clear();

                    CoPlayers.Remove(CoPlayer);

                    CoPlayer.EvilEgo.Orphanize();
                    CoPlayer.GoodEgo.Orphanize();

                    GroupEnemies.Remove(CoPlayer.EvilEgo);

                    CoPlayer.EvilEgo.RemoveFrom(FragileEntities.Items);
                    CoPlayer.GoodEgo.RemoveFrom(FragileEntities.Items);
                };

            RoutedActions.MoveCoPlayer.Direct =
                (ego, p) =>
                {
                    ego.GoodEgo.TweenMoveTo(p.x, p.y);
                };

            #endregion



            #region AddEnemy
            RoutedActions.AddEnemy.Direct +=
                (e, p) =>
                {
                    e.Name = "Enemy";

                    e.TeleportTo(p.x, p.y)
                    .AttachTo(CanvasOverlay)
                    .AddTo(FragileEntities.Items)
                    .AddTo(GroupEnemies);
                };
            #endregion

            #region cloud
            cloud1 = new EnemyCloud
           {
               PlaySound = play
           };

            cloud1.Members.ForEach(
                m =>
                {
                    // if a cloud member fires, it will go across network...
                    m.Element.FireBullet = RoutedActions.FireBullet;

                    this.SharedState.SharedObjects.Add(m.Element);

                    // we are adding enemies over network - but they actually are shared objects
                    RoutedActions.AddEnemy.Chained(m.Element, m.Element.ToPoint());
                }
            );

            cloud1.TickSounds =
                    new Sound[] {
						Sounds.duh0,
						Sounds.duh1,
						Sounds.duh2,
						Sounds.duh3,
					};

            cloud1.AttachTo(this.CanvasOverlay);




            cloud1.TickInterval.ValueChangedTo +=
                e => DebugDump.Write(new { TickInterval = e });



            //var CloudSpeedAcc = 1.04;
            //var CloudSpeed = 12.0;
            //var CloudMove = new Point();

            Action ResetCloudLocal =
                delegate
                {
                    cloud1.Speed = 12;
                    cloud1.NextMove.x = cloud1.Speed;
                    cloud1.NextMove.y = 0;



                    cloud1.TeleportTo(60, 80);
                    cloud1.TickInterval.Value = 1000;

                    // rebuild defense

                    foreach (var v in DefenseBlocks)
                    {
                        v.alpha = 1;
                    }

                    foreach (var v in KnownEgos)
                    {
                        v.GoodEgo.alpha = 1;
                        v.EvilEgo.alpha = 1;
                    }

                };

            ResetCloudLocal();

            bool ResetCloudSoonDisabled = false;

            RoutedActions.KillAllInvaders.Direct =
                delegate
                {
                    cloud1.Members.ForEach(m => m.Element.alpha = 0);
                };

            Action ResetCloudSoon =
                delegate
                {
                    if (ResetCloudSoonDisabled)
                        return;

                    ResetCloudSoonDisabled = true;

                    RoutedActions.KillAllInvaders.Chained();

                    // do not count evil mode
                    if (!Ego.EvilMode)
                        PlaysSurvived.Value++;

                    cloud1.TickInterval.Value = 0;
                    cloud1.TeleportTo(60, 80);

                    cloud1.Speed = 12;
                    cloud1.NextMove.x = cloud1.Speed;
                    cloud1.NextMove.y = 0;


                    3000.AtDelayDo(
                        delegate
                        {
                            cloud1.ResetColors();

                            ResetCloudLocal();

                            cloud1.ResetLives();

                            ResetCloudSoonDisabled = false;

                        }
                    );

                };


            cloud1.Tick +=
                delegate
                {
                    var r = cloud1.Warzone;

                    if (r == null)
                    {
                        ResetCloudSoon();

                        return;
                    }

                    //this.graphics.clear();
                    //this.graphics.beginFill(0xffffff);
                    //this.graphics.drawRect(r.x, r.y, r.width, r.height);

                    //DebugDump.Write(new { r.left, r.right, cloud1.FrontRow.Length });

                    if (r.bottom > DefenseY)
                    {
                        ResetCloudSoon();

                        return;
                    }

                    var Skip = 4 * (CoPlayers.Count + 1);

                    if (cloud1.Counter % Skip == 0)
                    {
                        // fire some bullets
                        var rr = cloud1.FrontRow.Random();

                        // invaders bullets should have different sound or be silent
                        rr.Element.FireBulletChained(1, new Point(rr.Element.x, rr.Element.y), new Point(rr.Element.x, DefaultHeight), Ego.GoodEgoY);

                        //rb.Silent = true;

                        //AddBullet.Chained(
                        //    rb
                        //);
                    }

                    var IsFarRight = r.right >= (DefaultWidth - EnemyCloud.DefaultCloudMargin);

                    if (cloud1.NextMove.x < 0)
                        IsFarRight = false;

                    var IsFarLeft = r.left <= (EnemyCloud.DefaultCloudMargin);

                    if (cloud1.NextMove.x > 0)
                        IsFarLeft = false;


                    var WillStartVerticalMovement = IsFarLeft || IsFarRight;


                    if (WillStartVerticalMovement && cloud1.NextMove.y == 0)
                    {


                        cloud1.NextMove.x = 0;
                        cloud1.NextMove.y = 8;

                        cloud1.Speed *= cloud1.SpeedAcc;
                    }
                    else
                    {
                        if (WillStartVerticalMovement)
                            cloud1.NextMove.y -= cloud1.Speed / 2;
                        else
                        {

                        }

                        if (cloud1.NextMove.y <= 0)
                        {
                            cloud1.NextMove.y = 0;

                            if (IsFarLeft)
                                cloud1.NextMove.x = cloud1.Speed;
                            else if (IsFarRight)
                                cloud1.NextMove.x = -cloud1.Speed;
                        }
                    }

                    //DebugDump.Write(new { CloudMove.x, CloudMove.y });

                    cloud1.MoveToOffset(cloud1.NextMove);

                };



            #endregion



            //AddEnemy.Chained(new EnemyA(), new Point(200, 200));
            //AddEnemy.Chained(new EnemyB(), new Point(240, 200));
            //AddEnemy.Chained(new EnemyC(), new Point(280, 200));
            //AddEnemy.Chained(new EnemyUFO(), new Point(160, 200));
            //AddEnemy.Chained(new EnemyBigGun(), new Point(120, 200));

            #region FireBullet

            RoutedActions.FireBullet.Direct =
                (StarShip starship, int Multiplier, Point From, Point To, double Limit, Action<BulletInfo> handler) =>
                {
                    var bullet = new SpriteWithMovement();

                    Multiplier = Math.Max(Multiplier, 1);

                    for (int i = 1; i <= Multiplier; i++)
                    {
                        bullet.graphics.beginFill(Colors.Green);
                        bullet.graphics.drawRect((i - Multiplier) * 2, -8, 1, 16);
                    }


                    bullet.StepMultiplier = 0.3;
                    bullet.MaxStep = 24;

                    if (From.y < To.y)
                    {
                        bullet.TeleportTo(From.x, From.y);
                        bullet.TweenMoveTo(To.x + 0.00001, To.y);

                        bullet.PositionChanged +=
                            delegate
                            {
                                if (bullet.y > Limit)
                                    bullet.Orphanize();
                            };
                    }
                    else
                    {
                        bullet.TeleportTo(From.x, From.y);
                        bullet.TweenMoveTo(To.x + 0.00001, To.y);


                        bullet.PositionChanged +=
                            delegate
                            {
                                if (bullet.y < Limit)
                                    bullet.Orphanize();
                            };
                    }

                    // it should not be null and provide the correct parent for the bullet
                    if (starship == null)
                        starship = this.Ego.ActiveEgo;

                    var bulletp = new BulletInfo(bullet.WithParent(starship)) { Multiplier = Multiplier };

                    // local only
                    FragileEntities.AddBullet(bulletp);

                    bulletp.Element.AttachTo(CanvasOverlay);
                    bulletp.Element.removed +=
                        delegate
                        {
                            FragileEntities.Bullets.Remove(bulletp);
                        };

                    if (!bulletp.Silent)
                        play(Sounds.firemissile);

                    if (handler != null)
                        handler(bulletp);
                };

            #endregion






            #region SetWeaponMultiplier

            RoutedActions.SetWeaponMultiplier.Direct =
                (p, value) =>
                {
                    p.CurrentBulletMultiplier.Value = value;
                };
            #endregion

            #region AddDamage
            RoutedActions.AddDamage.Direct +=
                (target, damage, shooter) =>
                {
                    target.TakeDamage(damage);

                    if (target.HitPoints <= 0)
                    {
                        // did we kill anything?
                        // shall we take credit?

                        if (GroupEnemies.Any(k => k == target))
                        {
                            cloud1.TickInterval.Value = Math.Max((cloud1.TickInterval.Value - 25),200);
                            cloud1.Speed *= cloud1.SpeedAcc;
                        }

                        // we shot a coplayer while in evil mode! yay!
                        if (shooter == Ego.EvilEgo)
                            if (KnownEgos.Any(k => k.GoodEgo == target))
                                this.RoutedActions.AddAchivementUFO.Chained();

                        #region award localplayer and upgrade weapon
                        if (shooter == Ego.ActiveEgo)
                        {
                            Statusbar.Score.Value += target.ScorePoints;

                            TryUpgradeWeapon();
                        }
                        #endregion


                        play(target.GetDeathSound());
                    }
                    else
                    {
                        play(Sounds.shortwhite);
                    }

                    //DebugDump.Write(
                    //    new
                    //    {
                    //        From = bullet.Parent.Name,
                    //        Delta = bullet.TotalDamage,
                    //        target.HitPoints,
                    //        To = target.Name
                    //    }
                    //);
                };
            #endregion



            #region FragileEntities
            this.FragileEntities.AddDamage = RoutedActions.AddDamage;

            this.FragileEntities.PrepareFilter =
                delegate
                {
                    var GroupGood = KnownEgos.Select(i => i.GoodEgo).ToArray();
                    var GroupEvil = GroupEnemies.ToArray();

                    this.FragileEntities.Filter =
                        (source, n) =>
                        {
                            // spare yourself
                            var query = source;

                            // spare coplayers in the same mode
                            if (GroupEnemies.Contains(n.Parent))
                                query = query.Where(x => !GroupEvil.Contains(x));
                            else
                                query = query.Where(x => !GroupGood.Contains(x));

                            return query;
                        };
                };
            #endregion

            this.RoutedActions.AddAchivementFiver.Direct =
                delegate
                {
                    play(Sounds.insertcoin);
                };

            this.RoutedActions.AddAchivementMaxGun.Direct =
                delegate
                {
                    play(Sounds.insertcoin);
                };

            this.RoutedActions.AddAchivementUFO.Direct =
                delegate
                {
                    play(Sounds.mothershiploop);
                };

            Action<RoutedActionInfoBase> BaseHandler =
                e => DebugDump.Write(new { e.EventName });

            // events for network
            // RoutedActions.AddDamage.BaseHandler += BaseHandler;
            RoutedActions.RestoreStarship.BaseHandler += BaseHandler;
            RoutedActions.AddAchivementFiver.BaseHandler += BaseHandler;
            RoutedActions.AddAchivementUFO.BaseHandler += BaseHandler;
            RoutedActions.AddAchivementMaxGun.BaseHandler += BaseHandler;

            //this.AddEnemy.BaseHandler += BaseHandler;
            ////this.AddBullet.BaseHandler += BaseHandler;
            //this.DoPlayerMovement.BaseHandler += BaseHandler;
            //this.SetWeaponMultiplier.BaseHandler += BaseHandler;

        }
Пример #48
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Updates the bullet info.
		/// </summary>
		/// <param name="bulInfo">The bullet info.</param>
		/// ------------------------------------------------------------------------------------
		private void UpdateBulletInfo(ref BulletInfo bulInfo)
		{
			if (m_rbNone.Checked)
				bulInfo.m_numberScheme = VwBulNum.kvbnNone;
			else if (m_rbBullet.Checked)
			{
				bulInfo.m_numberScheme = (VwBulNum)((int)VwBulNum.kvbnBulletBase +
					m_cboBulletScheme.SelectedIndex);
				bulInfo.FontInfo = m_BulletsFontInfo;
			}
			else if (m_rbNumber.Checked)
			{
				switch (m_cboNumberScheme.SelectedIndex)
				{
					case 0: bulInfo.m_numberScheme = VwBulNum.kvbnArabic; break;
					case 1: bulInfo.m_numberScheme = VwBulNum.kvbnRomanUpper; break;
					case 2: bulInfo.m_numberScheme = VwBulNum.kvbnRomanLower; break;
					case 3: bulInfo.m_numberScheme = VwBulNum.kvbnLetterUpper; break;
					case 4: bulInfo.m_numberScheme = VwBulNum.kvbnLetterLower; break;
					case 5: bulInfo.m_numberScheme = VwBulNum.kvbnArabic01; break;
				}
				bulInfo.m_start = m_nudStartAt.Value;
				bulInfo.m_textBefore = m_tbTextBefore.Text;
				bulInfo.m_textAfter = m_tbTextAfter.Text;
				bulInfo.FontInfo = m_NumberFontInfo;
			}
		}
Пример #49
0
 void Start()
 {
     bulInfo = gameObject.GetComponent<BulletInfo>();
 }
Пример #50
0
		public void DecodeBackwardCompatible_EverythingSet()
		{
			// Setup what we expect
			FontInfo expectedFontInfo = m_infoTable["TestStyle"].FontInfoForWs(-1);
			expectedFontInfo.m_fontName = new InheritableStyleProp<string>("Algerian");
			expectedFontInfo.m_fontSize = new InheritableStyleProp<int>(8000);
			expectedFontInfo.m_fontColor = new InheritableStyleProp<Color>(Color.Red);
			expectedFontInfo.m_backColor = new InheritableStyleProp<Color>(Color.White);
			expectedFontInfo.m_underline = new InheritableStyleProp<FwUnderlineType>(FwUnderlineType.kuntNone);
			expectedFontInfo.m_underlineColor = new InheritableStyleProp<Color>(Color.Black);
			expectedFontInfo.m_bold = new InheritableStyleProp<bool>(false);
			expectedFontInfo.m_italic = new InheritableStyleProp<bool>(false);
			expectedFontInfo.m_superSub = new InheritableStyleProp<FwSuperscriptVal>(FwSuperscriptVal.kssvOff);
			expectedFontInfo.m_offset = new InheritableStyleProp<int>(0);

			// Here's the BLOB.
			// we got these values by looking at the memory when debugging Data Notebook.
			byte[] byteBlob = new byte[] {0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
				0x00, 0x00, 0x06, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00,
				0x00, 0x08, 0x00, 0xff, 0x00, 0x00, 0x00, 0x09, 0x00, 0xff, 0xff, 0xff, 0x00,
				0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x00, 0x6c, 0x00, 0x67,
				0x00, 0x65, 0x00, 0x72, 0x00, 0x69, 0x00, 0x61, 0x00, 0x6e, 0x00, 0x00, 0x00 };
			string blob = new string(Encoding.Unicode.GetChars(byteBlob));

			BulletInfo bulletInfo = new BulletInfo();
			bulletInfo.EncodedFontInfo = blob;

			Assert.AreEqual(expectedFontInfo, bulletInfo.FontInfo);
		}
Пример #51
0
        public override void OnStart(StartState state)
        {
            base.OnStart (state);

            ParseWeaponType();
            ParseBulletDragType();

            bulletBallisticCoefficient = bulletMass / bulletDragArea * 1000;        //1000 to convert from tonnes to kilograms

            if(shortName == string.Empty)
            {
                shortName = part.partInfo.title;
            }

            foreach(var emitter in part.FindModelComponents<KSPParticleEmitter>())
            {
                emitter.emit = false;
            }

            if(roundsPerMinute >= 1500)
            {
                Events["ToggleRipple"].guiActiveEditor = false;
                Fields["useRippleFire"].guiActiveEditor = false;
            }

            if(airDetonation)
            {
                var detRange = (UI_FloatRange)Fields["defaultDetonationRange"].uiControlEditor;
                detRange.maxValue = maxAirDetonationRange;
            }
            else
            {
                Fields["defaultDetonationRange"].guiActive = false;
                Fields["defaultDetonationRange"].guiActiveEditor = false;
            }

            muzzleFlashEmitters = new List<KSPParticleEmitter>();
            foreach(Transform mtf in part.FindModelTransforms("muzzleTransform"))
            {
                KSPParticleEmitter kpe = mtf.GetComponent<KSPParticleEmitter>();
                muzzleFlashEmitters.Add(kpe);
                kpe.emit = false;
            }

            if(HighLogic.LoadedSceneIsFlight)
            {
                if(eWeaponType != WeaponTypes.Laser)
                {
                    if(bulletPool == null)
                    {
                        SetupBulletPool();
                    }
                    if(shellPool == null)
                    {
                        SetupShellPool();
                    }
                }

                //setup transforms
                fireTransforms = part.FindModelTransforms(fireTransformName);
                shellEjectTransforms = part.FindModelTransforms(shellEjectTransformName);

                //setup emitters
                foreach(var pe in part.FindModelComponents<KSPParticleEmitter>())
                {
                    pe.maxSize *= part.rescaleFactor;
                    pe.minSize *= part.rescaleFactor;
                    pe.shape3D *= part.rescaleFactor;
                    pe.shape2D *= part.rescaleFactor;
                    pe.shape1D *= part.rescaleFactor;

                    if(pe.useWorldSpace && !oneShotWorldParticles)
                    {
                        BDAGaplessParticleEmitter gpe = pe.gameObject.AddComponent<BDAGaplessParticleEmitter>();
                        gpe.part = part;
                        gaplessEmitters.Add(gpe);
                    }
                }

                //setup projectile colors
                projectileColorC = Misc.ParseColor255(projectileColor);
                startColorC = Misc.ParseColor255(startColor);

                //init and zero points
                targetPosition = Vector3.zero;
                pointingAtPosition = Vector3.zero;
                bulletPrediction = Vector3.zero;

                //setup audio
                SetupAudio();

                //laser setup
                if(eWeaponType == WeaponTypes.Laser)
                {
                    SetupLaserSpecifics();
                }
            }
            else if(HighLogic.LoadedSceneIsEditor)
            {
                fireTransforms = part.FindModelTransforms(fireTransformName);
            }

            //turret setup
            foreach(var turr in part.FindModulesImplementing<ModuleTurret>())
            {
                if(turr.turretID == turretID)
                {
                    turret = turr;
                    turret.SetReferenceTransform(fireTransforms[0]);
                    break;
                }
            }

            if(!turret)
            {
                Fields["onlyFireInRange"].guiActive = false;
                Fields["onlyFireInRange"].guiActiveEditor = false;
            }

            //setup animations
            if(hasDeployAnim)
            {
                deployState = Misc.SetUpSingleAnimation(deployAnimName, this.part);
                deployState.normalizedTime = 0;
                deployState.speed = 0;
                deployState.enabled = true;
            }
            if(hasFireAnimation)
            {
                fireState = Misc.SetUpSingleAnimation (fireAnimName, this.part);
                fireState.enabled = false;
            }
            bulletInfo = BulletInfo.bullets[bulletType];
            if (bulletInfo == null)
                Debug.Log("Failed To load bullet!");
            BDArmorySettings.OnVolumeChange += UpdateVolume;
        }