Inheritance: MonoBehaviour
Example #1
0
    public void PickUpWeapon(Weapon weapon)
    {
        if (this.weapon != null) {
            this.weapon.collider.isTrigger = false;
            this.weapon.rigidbody.useGravity = true;
            this.weapon.rigidbody.velocity = new Vector3(0.0f, 1.0f, 0.0f);

            Vector3 dir = (transform.position - Camera.main.transform.position).normalized;
            dir *= 4.0f;
            dir.y = 1.0f;

            this.weapon.transform.parent = null;
            this.weapon.rigidbody.position = transform.position + dir;
            this.weapon.deactivate();
        }

        this.weapon = weapon;
        this.weapon.activate(holdingHand, ammoScript);
        weapon.collider.isTrigger = true;
        weapon.rigidbody.useGravity = false;

        weapon.transform.parent = holdingHand;
        weapon.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);

        //Start();
    }
Example #2
0
    public override void Init(Creature ownerCreature, Weapon weapon, Weapon.FiringDesc targetAngle)
    {
        base.Init(ownerCreature, weapon, targetAngle);

        transform.parent = ownerCreature.WeaponHolder.transform;
        transform.localPosition = Vector3.zero;
    }
Example #3
0
    public Weapon EquipWeapon(Weapon item, bool leftHand)
    {
        if (item == null)
            return item;

        if (item.Location != Equipment.EquipmentLocation.Weapon  && item.Location != Equipment.EquipmentLocation.OffHand)
            return item;

        // no dual wielding
        if (item.Location == Equipment.EquipmentLocation.Weapon)
        {
            if (leftHand && RightHand != null && RightHand.Location == Equipment.EquipmentLocation.Weapon)
                return item;

            if (!leftHand && LeftHand != null && LeftHand.Location == Equipment.EquipmentLocation.Weapon)
                return item;
        }

        Weapon returnedItem = leftHand ? LeftHand : RightHand;
        if (leftHand)
            LeftHand = item;
        else
            RightHand = item;

        return returnedItem;
    }
        protected override void ExecuteAddSupplementCommand(string[] commandWords)
        {
            string supplementId = commandWords[1];
            string id = commandWords[2];

            var unitForAdding = this.GetUnit(id);
            ISupplement supplement = null;
            switch (supplementId)
            {
                case "AggressionCatalyst":
                    supplement =  new AggressionCatalyst();
                    break;
                case "Weapon":
                   supplement =  new Weapon();
                    break;
                case "PowerCatalyst":
                    supplement = new PowerCatalyst();
                    break;
                case "HealthCatalyst":
                    supplement = new HealthCatalyst();
                    break;
                default:
                    break;
            }

            unitForAdding.AddSupplement(supplement);
        }
Example #5
0
 public static new Weapon genItem()
 {
     Weapon i = new Weapon();
     i.itemID = ItemDatabase.GenerateID();
     i.billboard = false;
     return i;
 }
Example #6
0
 protected override void ExecuteAddSupplementCommand(string[] commandWords)
 {
     Unit targetUnit = null;
     switch (commandWords[1])
     {
         case "PowerCatalyst":
             var powerCatalyst = new PowerCatalyst();
             targetUnit = GetUnit(commandWords[2]);
             targetUnit.AddSupplement(powerCatalyst);
             break;
         case "HealthCatalyst":
             var healthCatalyst = new HealthCatalyst();
             targetUnit = GetUnit(commandWords[2]);
             targetUnit.AddSupplement(healthCatalyst);
             break;
         case "AggressionCatalyst":
             var aggressionCatalyst = new AggressionCatalyst();
             targetUnit = GetUnit(commandWords[2]);
             targetUnit.AddSupplement(aggressionCatalyst);
             break;
         case "Weapon":
             var weapon = new Weapon();
             targetUnit = GetUnit(commandWords[2]);
             targetUnit.AddSupplement(weapon);
             break;
         default:
             break;
     }
 }
	void NewWeaponEquipped(Weapon.WeaponType weaponType)
	{
		//reset weapon animations
		animator.Rebind();

		//activate/deactivate specific animator layers when new weapons get equipped
		if (weaponType == Weapon.WeaponType.Sword)
		{
			animator.SetLayerWeight(2, 1);
			animator.SetLayerWeight(3, 0);
			animator.SetLayerWeight(4, 0);
		}
		else if (weaponType == Weapon.WeaponType.Axe)
		{
			animator.SetLayerWeight(2, 0);
			animator.SetLayerWeight(3, 1);
			animator.SetLayerWeight(4, 0);
		}
		else if (weaponType == Weapon.WeaponType.Hammer)
		{
			animator.SetLayerWeight(2, 0);
			animator.SetLayerWeight(3, 0);
			animator.SetLayerWeight(4, 1);
		}
	}
    public override void Init(Creature ownerCreature, Weapon weapon, Weapon.FiringDesc targetAngle)
    {
        base.Init(ownerCreature, weapon, targetAngle);

        m_weapon = weapon as GuidedRocketLauncher;
        m_selfDestoryTime = Time.time + 5f;
    }
    public void TakesHit(string weaponType, Weapon weapon, Collider2D coll, int hitFrom)
    {
        // calculate damage
        player.HP -= (int)(weapon.damage * DIFFICULTY_DAMAGE_MODIFIER);

        // produce effects
        // params for ShakeCamera = duration, strength, vibrato, randomness
        Messenger.Broadcast<float, float, int, float>("shake camera", .5f, .3f, 20, 5f);
        Messenger.Broadcast<int>("reduce hp", player.HP);

        // float xDistance = hitFrom == LEFT ? 2f : -2f;
        // transform.DOJump(new Vector3(transform.position.x + xDistance, transform.position.y, transform.position.z), .2f, 1, .5f, false);

        if (hitFrom == RIGHT)
        {
            BroadcastMessage("RepulseToLeft", 5.0F);
        }
        else
        {
            BroadcastMessage("RepulseToRight", 5.0F);
        }

        if (player.HP > 0)
        {
            MFX.FadeToColorAndBack(spriteRenderer, MCLR.bloodRed, 0f, .2f);
        }
        else
        {
            Messenger.Broadcast<string, Collider2D, int>("player dead", "projectile", coll, hitFrom);
        }
    }
 void Start()
 {
     myTeamId = GetComponent<TeamMember> ().teamId;
     atkController = GetComponent<AttackController> ();
     weapon = atkController.currentWeapon;
     myRenderer = GetComponentInChildren<MeshRenderer> ();
 }
Example #11
0
 new void Awake()
 {
     base.Awake();
     weapon = GetComponent<Weapon>();
     MAX_HEALTH *= 10f;
     health = MAX_HEALTH;
 }
    private void Awake()
    {
        m_hWeapon = this.GetComponent<Weapon>();
        Owner = GetComponent<Actor>();
        m_hIdle             = new StateIdle(this);
        m_hPatrol           = new StatePatrol(this);

        switch ((int)AimMode)
        {
            case 1:
                m_hPatrol.Next = new StateAimBallistic(this); 
                break;
            case 2:
                m_hPatrol.Next = new StateAimDirect(this); 
                break;
        }


        m_hPatrol.Next.Next = m_hPatrol;

        m_hCurrent          = m_hPatrol;
        m_hCurrent.OnStateEnter();

        
    }
Example #13
0
 private void SpawnMuzzleFlare(Weapon weapon)
 {
     var flare = ObjectPool.Instance.GetObject(MuzzleFlare);
     flare.transform.position = weapon.Emitter.position;
     flare.transform.rotation = weapon.Emitter.rotation;
     flare.transform.parent = weapon.Emitter;
 }
	// note: ProjectileContainers contain simple dummy values, which are
	// then replaced by data that's passed-in via projectile objects
	void Init(Weapon incoming)
	{
		weapon                = incoming;
		weaponType            = incoming.weaponType;
		alreadyCollided       = false;
		iconSprite            = incoming.iconSprite;
		title                 = incoming.title;
		damage                = incoming.damage;
		hp                    = incoming.hp;
		rateOfAttack          = incoming.rateOfAttack;
		spriteRenderer.sprite = incoming.carriedSprite;
		speed                 = incoming.speed;
		maxDistance           = incoming.maxDistance;
		lob                   = incoming.lob;
		lobGravity            = incoming.lobGravity;
		fadeIn                = incoming.fadeIn;
		collider2D.enabled    = true;
		origin                = new Vector3(transform.position.x, transform.position.y, transform.position.z);

		// initialize animation controller if projectile is animated
		if (incoming.GetComponent<Weapon>().animatedProjectile)
		{
			anim = (RuntimeAnimatorController)RuntimeAnimatorController.Instantiate
						(Resources.Load(("Sprites/Projectiles/" + incoming.name + "_0"), typeof(RuntimeAnimatorController)));
			animator.runtimeAnimatorController = anim;
			animator.speed = .5f;
		}

		InvokeRepeating("CheckDistanceTraveled", 1, 0.3F);
	}
Example #15
0
 void Start()
 {
     _collider = GetComponent<Collider2D>();
     _rigidbody = GetComponent<Rigidbody2D>();
     weapon = GetComponentInChildren<Weapon>();
     anim = GetComponent<Animator>();
     SP = GetComponent<SpecialPower>();
     distToGround = _collider.bounds.extents.y;
     UpdateHealthSlider();
     GameManager.instance.players.Add(this);
     GameManager.instance.SetControls();
     if (useSecondaryControls)
     {
         keys[0] = KeyCode.W;
         keys[1] = KeyCode.Space;
         keys[2] = KeyCode.D;
         keys[3] = KeyCode.A;
         keys[4] = KeyCode.LeftShift;
         facingRight = true;
     }
     else
     {
         keys[0] = KeyCode.UpArrow;
         keys[1] = KeyCode.Return;
         keys[2] = KeyCode.RightArrow;
         keys[3] = KeyCode.LeftArrow;
         keys[4] = KeyCode.RightShift;
         transform.localScale = new Vector3(-1, 1, 1);
         facingRight = false;
     }
 }
/** ----------------------------------------------------------------------------- Methods -----------------------------------------------------------------------------------------------------*/

    void Start(){
        //small Weapons
        wood_sword_small = GameObject.Find("Wood_Sword_Small").GetComponent<Weapon>();
        wood_sword_big = GameObject.Find("Wood_Sword_Big").GetComponent<Weapon>();
        sword_1_small = GameObject.Find("Sword_1_Small").GetComponent<Weapon>();
        bow_small = GameObject.Find("Bow_Small").GetComponent<Weapon>();
        wand_small = GameObject.Find("Wand_Small").GetComponent<Wand>();
        //middle Weapons
        sword_1_middle = GameObject.Find("Sword_1_Middle").GetComponent<Weapon>();
        sword_2_small = GameObject.Find("Sword_2_Small").GetComponent<Weapon>();
        mace_1 = GameObject.Find("Mace_1").GetComponent<Weapon>();
        axe = GameObject.Find("Axe").GetComponent<Weapon>();
        wand_middle = GameObject.Find("Wand_Middle").GetComponent<Wand>();
        //big Weapons
        sword_1_big = GameObject.Find("Sword_1_Big").GetComponent<Weapon>();
        sword_2_big = GameObject.Find("Sword_2_Big").GetComponent<Weapon>();
        mace_2 = GameObject.Find("Mace_2").GetComponent<Weapon>();
        axe_big = GameObject.Find("Axe_Big").GetComponent<Weapon>();
        bow_big = GameObject.Find("Bow_Big").GetComponent<Weapon>();
        wand_big = GameObject.Find("Wand_Big").GetComponent<Wand>();
        //Shields
        shield_small = GameObject.Find("Shield_Small").GetComponent<Shield>();
        shield_big = GameObject.Find("Shield_Big").GetComponent<Shield>();
        //init Lists and Dictionaries
        initListsAndDictionaries();
             
    }
        /// <summary>
        /// Determines the level.
        /// </summary>
        /// <param name="skills">The skills.</param>
        /// <param name="weapon">The weapon.</param>
        public static int DetermineCombatLevel(SkillsContainer skills, Weapon weapon)
        {
            double a = skills.Attack + weapon.APoints;
            double d = skills.Defense / skills.Handicap;

            return Convert.ToInt32(Math.Ceiling(a + d));
        }
	public DamageMessage (float dmg, Vector3 dir, float dmgFrce, Weapon.DamageBias bs, Weapon.WeaponType tp, Ship own)
	{
		damage = dmg;
		damageDirection = dir;
		damageForce = dmgFrce;
		bias = bs;
		type = tp;
		
		if (own != null)
			owner = own.gameObject;
		else
			return;
		
		hasShip = true;
		try
		{
			viewID = own.GetComponent<PhotonView>().viewID;
		}
		catch
		{
			Debug.Log(owner.name  + " does not have a photon View ID");
		}
		
		if (own is AiShip)
			player = false;
		else
			player = true;
	}
Example #19
0
 private void onKeyDown(object sender, KeyEventArgs e)
 {
     if (e.KeyCode == Keys.K)
     {
         if(zulfat != null)
         {
             zulfat.Delete();
         }
         UI.Notify("~r~ZULFAT ACTIVATED");
         zulfat = World.CreatePed(PedHash.Trevor, Game.Player.Character.Position + Game.Player.Character.ForwardVector);
         rifle = zulfat.Weapons.Give(WeaponHash.Minigun, 100, true, true);
         rpg = zulfat.Weapons.Give(WeaponHash.RPG, 100, false, true);
         knife = zulfat.Weapons.Give(WeaponHash.Knife, 1, false, true);
         axe = zulfat.Weapons.Give(WeaponHash.Hatchet, 1, false, true);
         hand = zulfat.Weapons.Give(WeaponHash.Unarmed, 1, false, true);
         rpg.InfiniteAmmo = true;
         rpg.InfiniteAmmoClip = true;
         axe.InfiniteAmmo = true;
         axe.InfiniteAmmoClip = true;
         knife.InfiniteAmmo = true;
         knife.InfiniteAmmoClip = true;
         zulfat.Weapons.Current.InfiniteAmmo = true;
         zulfat.Weapons.Current.InfiniteAmmoClip = true;
         zulfat.AddBlip();
         zulfat.IsInvincible = true;
         UI.Notify(zulfat.TaskSequenceProgress.ToString());
         ADD_PEDS_TO_LIST();
     }
     if (e.KeyCode == Keys.Y)
     {
         World.CreateRandomPed(Game.Player.Character.Position + Game.Player.Character.RightVector);
     }
 }
Example #20
0
 void setStance(BaseStance toSet)
 {
     currStance = toSet;
     stanceText.color = currStance.colour;
     stanceText.text = currStance.text;
     weapon = ((Weapon)GetComponentInChildren (currStance.weapon));
 }
Example #21
0
    void Awake()
    {
        foreach ( Item item in ItemManager.Instance.items ) {
            if (item.name == this.transform.name) {
                me = item as Weapon;
            }
        }
        foreach (Transform child in transform) {
            if (child.name == "barrel")
                barrel = child;
        }
        shotAngles = new Vector3[3] {Vector3.right, new Vector3(0.8f,0.8f,0).normalized , new Vector3(0.8f,-0.8f,0).normalized};

        //foreach (Transform t in transform)
        //{
        //	if (t.name == "Grenade") grenade = t.gameObject;
        //}
        foreach (Transform child in GameObject.FindWithTag("Player").transform)
        {
            if (child.name == "bullet")
                bullet = child.gameObject;
            else if (child.name == "rocket")
                rocket = child.gameObject;
            else if (child.name == "semiautobullet")
                semiautobullet = child.gameObject;
            else if (child.name == "Gun")
                primaryGun = child.gameObject;
        }

        animator = barrel.GetComponent<Animator>();
    }
Example #22
0
 public UnitEquipment( Weapon weaponPrimary, Weapon weaponSecondary, Equippable[] misc, Biomod biomod = null )
 {
     this.weaponPrimary = weaponPrimary;
     this.weaponSecondary = weaponSecondary;
     this.misc = misc;
     this.biomod = biomod;
 }
Example #23
0
    public static Weapon Morph(Weapon mine, Weapon other)
    {
        Weapon combined = new Weapon();

        float targetStrength = Mathf.Max(mine.GetStrength(), other.GetStrength()) + MORPH_STRENGTH_INCREASE;
        float strength = 0;

        foreach (BulletSpawner bs in mine.bulletSpawners) {
            if (UnityEngine.Random.value < CHANCE_TO_KEEP_WEAPON) {
                strength += bs.GetStrength(combined);
                combined.bulletSpawners.Add(bs);
            }
        }

        foreach (BulletSpawner bs in other.bulletSpawners) {
            if (UnityEngine.Random.value < CHANCE_TO_GAIN_WEAPON) {
                strength += bs.GetStrength(combined);
                combined.bulletSpawners.Add(bs);
            }
        }

        while (strength < targetStrength) {
            BulletSpawner bulletSpawner = BulletSpawner.Random();
            strength += bulletSpawner.GetStrength(combined);
            combined.bulletSpawners.Add(bulletSpawner);
        }

        return combined;
    }
Example #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello");

            Weapon stick = new Weapon("Stick", 1, WeaponType.Blunt, 2);

            CharacterBase player = Player.GetInstance();

            Console.WriteLine(player);

            player.EquipWeapon(stick);

            Console.WriteLine(player);
            Console.WriteLine("Player MaxHealth : " + player.MaxHealth);
            Console.WriteLine("Adding +10 health buff to player");
            BaseEffect effect = new MaxHealthAdditionEffect(10);
            player.EffectsManager.AddEffect(effect);

            Console.WriteLine("Player MaxHealth : " + player.MaxHealth);

            Console.WriteLine("Removing +10 health buff from player");
            player.EffectsManager.RemoveEffect(effect);

            Console.WriteLine("Player MaxHealth : " + player.MaxHealth);

            Console.WriteLine("Press Enter to Exit");
            Console.ReadKey();
        }
Example #25
0
 public void AddWeapon(string key, Weapon weapon)
 {
     if (!GetWeapons().ContainsKey(key))
     {
         _weapons.Add(key, weapon);
     }
 }
Example #26
0
	void Start()
	{
		projectile		= GetComponent<ProjectileManager>();
		weapon			= GetComponentInChildren<Weapon>();
		target			= GameObject.Find(PLAYER).transform;
		attackInterval = Rand.Range(1.5f, 2.5f);
	}
Example #27
0
	// Use this for initialization
	void Start () {

        Inventory = new List<Item>();

        if (GodMode)
        {
            Weapon w = new Weapon(WeaponType.Rifle);
            Inventory.Add(w);
        }

        //set active (for now)
        activeItem = Inventory[0];

        Facing = FacingDirection.Left;
        Animation = AnimateState.Down;
        
        PlayerCamera = Camera.main;
        TargetPosition = transform.position;

        PlayerConvText = GameObject.Find("PlayerConvText");

        textures = new Texture[4];

        textures[0] = (Texture)UnityEditor.AssetDatabase.LoadAssetAtPath("Assets\\Resources\\Drawings\\Characters\\theblind_back.png", typeof(Texture));
        textures[1] = (Texture)UnityEditor.AssetDatabase.LoadAssetAtPath("Assets\\Resources\\Drawings\\Characters\\theblind_front.png", typeof(Texture));
        textures[2] = (Texture)UnityEditor.AssetDatabase.LoadAssetAtPath("Assets\\Resources\\Drawings\\Characters\\theblind_left.png", typeof(Texture));
        textures[3] = (Texture)UnityEditor.AssetDatabase.LoadAssetAtPath("Assets\\Resources\\Drawings\\Characters\\theblind_right.png", typeof(Texture));

        GetComponent<Renderer>().material.mainTexture = textures[2];
	}
Example #28
0
 void Start()
 {
     player_controller_ = GetComponent<PlayerController>();
     var weapon_attacher = GetComponent<WeaponAttacher>();
     right_weapon_ = weapon_attacher.getRightWeapon;
     left_weapon_ = weapon_attacher.getLeftWeapon;
 }
	protected virtual void Awake()
	{
		if(Weapon == null)
		{
			Weapon = GetComponent<Weapon>() ?? GetComponentInParent<Weapon>();
		}
	}
    // Use this for initialization
    void Start()
    {
        texture = new Texture2D(128, 128,TextureFormat.RGB24,false);
        style = new GUIStyle();

        texture2 = new Texture2D(128, 128,TextureFormat.RGB24,false);
        style = new GUIStyle();

        weapon = GetComponent<Weapon>();
        ship = GetComponent<Ship>();
        maxHealth = ship.GetHealth();
        curHealth = maxHealth;
        maxCool = weapon.GetcdTime();
        curCool = maxCool;
        for (int y = 0; y < texture.height; ++y)
        {
            for (int x = 0; x < texture.width; ++x)
            {
                Color color = new Color(238, 0, 238);
                texture.SetPixel(x, y, color);
            }
        }
        texture.Apply();

        for (int y = 0; y < texture2.height; ++y)
        {
            for (int x = 0; x < texture2.width; ++x)
            {
                Color color = new Color(255, 0, 0);
                texture2.SetPixel(x, y, color);
            }
        }
        texture2.Apply();
    }
Example #31
0
 public void Setup(Weapon weapon)
 {
     this.weapon = weapon;
 }
Example #32
0
    private void ProcessInput(float delta)
    {
        //  -------------------------------------------------------------------
        //  Walking
        _dir = new Vector3();
        Transform camXform = Camera.GlobalTransform;

        Vector2 inputMovementVector = new Vector2();

        if (Input.IsActionPressed("movement_forward"))
        {
            inputMovementVector.y += 1;
        }
        if (Input.IsActionPressed("movement_backward"))
        {
            inputMovementVector.y -= 1;
        }
        if (Input.IsActionPressed("movement_left"))
        {
            inputMovementVector.x -= 1;
        }
        if (Input.IsActionPressed("movement_right"))
        {
            inputMovementVector.x += 1;
        }

        inputMovementVector = inputMovementVector.Normalized();

        // Basis vectors are already normalized.
        _dir += -camXform.basis.z * inputMovementVector.y;
        _dir += camXform.basis.x * inputMovementVector.x;
        //  -------------------------------------------------------------------

        //  -------------------------------------------------------------------
        //  Jumping
        if (IsOnFloor() && Input.IsActionJustPressed("movement_jump"))
        {
            _vel.y = JumpSpeed;
        }
        //  -------------------------------------------------------------------

        //  -------------------------------------------------------------------
        //  Sprinting
        if (Input.IsActionPressed("movement_sprint"))
        {
            _isSprinting = true;
        }
        else
        {
            _isSprinting = false;
        }
        //  -------------------------------------------------------------------

        //  -------------------------------------------------------------------
        //  Turning the flashlight on/off

        if (Input.IsActionJustPressed("flashlight"))
        {
            if (_flashlight.IsVisibleInTree())
            {
                _flashlight.Hide();
            }
            else
            {
                _flashlight.Show();
            }
        }

        //  -------------------------------------------------------------------
        //  Changing _weapons

        int _weaponChangeNumber = _weaponNameToNumber[_currentWeaponName];

        if (Input.IsActionJustPressed("Weapon1"))
        {
            _weaponChangeNumber = 0;
        }
        if (Input.IsActionJustPressed("Weapon2"))
        {
            _weaponChangeNumber = 1;
        }
        if (Input.IsActionJustPressed("Weapon3"))
        {
            _weaponChangeNumber = 2;
        }
        if (Input.IsActionJustPressed("Weapon4"))
        {
            _weaponChangeNumber = 3;
        }

        if (Input.IsActionJustPressed("shift_weapon_positive"))
        {
            _weaponChangeNumber++;
        }
        if (Input.IsActionJustPressed("shift_weapon_negative"))
        {
            _weaponChangeNumber--;
        }

        _weaponChangeNumber = Mathf.Clamp(_weaponChangeNumber, 0, _weaponNumberToName.Count);

        if (_weaponNumberToName[_weaponChangeNumber] != _currentWeaponName)
        {
            if (!_reloadingWeapon && !_changingWeapon)
            {
                _changingWeaponName = _weaponNumberToName[_weaponChangeNumber];
                _changingWeapon     = true;
                _mouseScrollValue   = _weaponChangeNumber;
            }
        }
        //  -------------------------------------------------------------------

        //  -------------------------------------------------------------------
        //  Firing Weapon
        if (Input.IsActionPressed("fire") && !_changingWeapon && !_reloadingWeapon)
        {
            Weapon _currentWeapon = _weapons[_currentWeaponName];
            if (_currentWeapon != null && _currentWeapon.AmmoInWeapon > 0)
            {
                if (AnimationPlayer.CurrentState == _currentWeapon.IdleAnimName)
                {
                    AnimationPlayer.CallbackFunction = GD.FuncRef(this, nameof(FireBullet));
                    AnimationPlayer.SetAnimation(_currentWeapon.FireAnimName);
                }
            }
            else
            {
                _reloadingWeapon = true;
            }
        }
        //  -------------------------------------------------------------------

        //  -------------------------------------------------------------------
        //	Reloading
        if (!_reloadingWeapon && !_changingWeapon && Input.IsActionJustPressed("reload"))
        {
            Weapon _currentWeapon = _weapons[_currentWeaponName];
            if (_currentWeapon != null && _currentWeapon.CanReload)
            {
                string _currentAnimState = AnimationPlayer.CurrentState;
                bool   _isReloading      = false;
                foreach (string _weapon in _weapons.Keys)
                {
                    Weapon _weaponNode = _weapons[_weapon];
                    if (_weaponNode != null && _currentAnimState == _weaponNode.ReloadingAnimName)
                    {
                        _isReloading = true;
                    }
                }
                if (!_isReloading)
                {
                    _reloadingWeapon = true;
                }
            }
        }
        //  -------------------------------------------------------------------

        //  -------------------------------------------------------------------
        //	Changing and throwing grenades

        if (Input.IsActionJustPressed("change_grenade"))
        {
            if (_currentGrenade == 0)
            {
                _currentGrenade = 1;
            }
            else if (_currentGrenade == 1)
            {
                _currentGrenade = 0;
            }
        }

        if (Input.IsActionJustPressed("fire_grenade") && _grenadeAmmounts[_currentGrenade] > 0)
        {
            _grenadeAmmounts[_currentGrenade]--;

            Grenade _grenadeClone;
            if (_currentGrenade == 0)
            {
                _grenadeClone = (FragGrenade)_fragGrenadeScene.Instance();
            }
            else
            {
                _grenadeClone = (StickyGrenade)_stickyGrenadeScene.Instance();
                // Sticky grenades will stick to the player if we do not pass ourselves
                _grenadeClone.PlayerBody = this;
            }

            GetTree().Root.AddChild(_grenadeClone);
            _grenadeClone.GlobalTransform = GetNode <Spatial>("Rotation_Helper/FragGrenade_Toss_Pos").GlobalTransform;
            _grenadeClone.ApplyImpulse(new Vector3(0, 0, 0), _grenadeClone.GlobalTransform.basis.z * FragGrenadeThrowForce);
        }
        //  -------------------------------------------------------------------

        //  -------------------------------------------------------------------
        //	Grabbing and throwing objects
        if (Input.IsActionJustPressed("fire") && _currentWeaponName == "UNARMED")
        {
            if (_grabbedObject == null)
            {
                PhysicsDirectSpaceState _state = GetWorld().DirectSpaceState;

                Vector2 _centerPosition          = GetViewport().Size / 2;
                Vector3 _rayFrom                 = Camera.ProjectRayOrigin(_centerPosition);
                Vector3 _rayTo                   = _rayFrom + Camera.ProjectRayNormal(_centerPosition) * ObjectGrabRayDistance;
                Godot.Collections.Array _exclude = new Godot.Collections.Array();
                _exclude.Add(this);
                _exclude.Add(GetNode <Area>("Rotation_Helper/Gun_Fire_Points/Knife/Area"));
                Godot.Collections.Dictionary _rayResult = _state.IntersectRay(_rayFrom, _rayTo, _exclude);
                if (_rayResult.Count != 0 && _rayResult["collider"] is RigidBody)
                {
                    _grabbedObject = _rayResult["collider"];
                    RigidBody _grabbedRigid = (RigidBody)_grabbedObject;
                    _grabbedRigid.Mode = RigidBody.ModeEnum.Static;

                    _grabbedRigid.CollisionLayer = 0;
                    _grabbedRigid.CollisionMask  = 0;
                }
            }
            else
            {
                _grabbedRigid = (RigidBody)_grabbedObject;

                _grabbedRigid.Mode = RigidBody.ModeEnum.Rigid;

                _grabbedRigid.ApplyImpulse(new Vector3(0, 0, 0), -Camera.GlobalTransform.basis.z.Normalized() * ObjectThrowForce);

                _grabbedRigid.CollisionLayer = 1;
                _grabbedRigid.CollisionMask  = 1;

                _grabbedRigid  = null;
                _grabbedObject = null;
            }
        }
        if (_grabbedObject != null)
        {
            _grabbedRigid = (RigidBody)_grabbedObject;
            Transform _transform = new Transform(_grabbedRigid.GlobalTransform.basis, Camera.GlobalTransform.origin + (-Camera.GlobalTransform.basis.z.Normalized() * ObjectGrabDistance));
            _grabbedRigid.GlobalTransform = _transform;
        }
        //  -------------------------------------------------------------------

        //  -------------------------------------------------------------------
        //	Pause Popup
        if (Input.IsActionJustPressed("ui_cancel"))
        {
            if (_pausePopup == null)
            {
                _pausePopup        = (PausePopup)_pausePopupScene.Instance();
                _pausePopup.Player = this;

                _globals.CanvasLayer.AddChild(_pausePopup);
                _pausePopup.PopupCentered();

                Input.SetMouseMode(Input.MouseMode.Visible);

                GetTree().Paused = true;
            }
            else
            {
                Input.SetMouseMode(Input.MouseMode.Captured);
                _pausePopup = null;
            }
        }
        //  -------------------------------------------------------------------
    }
Example #33
0
    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        // Constructor
        _vel = new Vector3();
        _dir = new Vector3();

        // Assigns relevant nodes to variables.
        Camera             = GetNode <Camera>("Rotation_Helper/Camera");
        _rotationHelper    = GetNode <Spatial>("Rotation_Helper");
        _flashlight        = GetNode <SpotLight>("Rotation_Helper/Flashlight");
        AnimationPlayer    = GetNode <AnimationManager>("Rotation_Helper/Model/Animation_Player");
        _simpleAudioPlayer = ResourceLoader.Load <PackedScene>("res://common/audioplayer/SimpleAudioPlayer.tscn");
        _uiStatusLabel     = GetNode <Label>("HUD/Panel/Gun_label");
        Vector3 GunAimPointPos = GetNode <Spatial>("Rotation_Helper/Gun_Aim_Point").GlobalTransform.origin;

        _globals = GetNode <Globals>("/root/Globals");

        // Assigns relevant scenes to variables.
        _fragGrenadeScene   = ResourceLoader.Load <PackedScene>("res://weaponry/grenades/frag/FragGrenade.tscn");
        _stickyGrenadeScene = ResourceLoader.Load <PackedScene>("res://weaponry/grenades/sticky/StickyGrenade.tscn");
        _pausePopupScene    = ResourceLoader.Load <PackedScene>("res://ui/popups/pause/PausePopup.tscn");

        // Dictionary for Weapon Nodes.
        _weapons.Add("KNIFE", GetNode <Knife>("Rotation_Helper/Gun_Fire_Points/Knife"));
        _weapons.Add("RIFLE", GetNode <Rifle>("Rotation_Helper/Gun_Fire_Points/Rifle"));
        _weapons.Add("PISTOL", GetNode <Pistol>("Rotation_Helper/Gun_Fire_Points/Pistol"));
        _weapons.Add("UNARMED", null);

        // Setup each Weapon in _weapons Dictionary
        foreach (string Weapon in _weapons.Keys)
        {
            if (_weapons[Weapon] != null)
            {
                Weapon _weaponNode = _weapons[Weapon];
                _weaponNode.Playernode = this;
                // Make Weaponnode point towards the aim position.
                _weaponNode.LookAt(GunAimPointPos, new Vector3(0, 1, 0));
                // Rotate it by 180° on the Y axis.
                _weaponNode.RotateObjectLocal(new Vector3(0, 1, 0), Mathf.Deg2Rad(180));
            }
        }

        // Weapon Dictionaries.
        _weaponNumberToName.Add(0, "UNARMED");
        _weaponNumberToName.Add(1, "KNIFE");
        _weaponNumberToName.Add(2, "PISTOL");
        _weaponNumberToName.Add(3, "RIFLE");

        _weaponNameToNumber.Add("UNARMED", 0);
        _weaponNameToNumber.Add("KNIFE", 1);
        _weaponNameToNumber.Add("PISTOL", 2);
        _weaponNameToNumber.Add("RIFLE", 3);

        // Variables relevant for character actions.
        _changingWeapon              = false;
        _changingWeaponName          = "UNARMED";
        _currentWeaponName           = "UNARMED";
        _isSprinting                 = false;
        _reloadingWeapon             = false;
        _mouseSensitivityScrollWheel = 0.08f;
        _currentGrenade              = 0;
        _deadTime = 0;
        _isDead   = false;

        // Character stats
        _grenadeNames = new string[] { "Frag Grenade", "Sticky Grenade" };
        RespawnTime   = 4;

        // The method being called once an fire animation plays.
        AnimationPlayer.CallbackFunction = GD.FuncRef(this, nameof(FireBullet));

        Camera.Far = 1000;
        // Set Transformation to spawnpoint
        // GlobalTransform = _globals.GetRespawnPosition(GlobalTransform.basis);

        // Captures mouse, used as indication that setup is complete.
        Input.SetMouseMode(Input.MouseMode.Captured);
    }
Example #34
0
        public Scheme GenerateScheme(Random rng, SchemeVersion version)
        {
            Scheme scheme = new Scheme(version, ExtendedOptionsDataVersion);

            //Generate values for every setting.
            int settingsCount = Math.Min(scheme.Settings.Length, _settingGenerators.Length);

            for (int i = 0; i < settingsCount; ++i)
            {
                ValueGenerator valueGenerator = _settingGenerators[i];

                if (valueGenerator != null)
                {
                    SettingTypes settingType = (SettingTypes)i;
                    Setting      setting     = scheme.Access(settingType);
                    Debug.Assert(setting != null);

                    setting.SetValue(valueGenerator.GenerateValue(rng), valueGenerator);
                }
            }

            //Generate values for every weapon.
            int weaponsCount = Math.Min(scheme.Weapons.Length, _weaponGenerators.Length);

            for (int i = 0; i < weaponsCount; ++i)
            {
                WeaponGenerator weaponGenerator = _weaponGenerators[i];

                for (int j = 0; j < (int)WeaponSettings.Count; ++j)
                {
                    WeaponSettings weaponSetting  = (WeaponSettings)j;
                    ValueGenerator valueGenerator = weaponGenerator.Get(weaponSetting);

                    if (valueGenerator != null)
                    {
                        WeaponTypes weaponType = (WeaponTypes)i;
                        Weapon      weapon     = scheme.Access(weaponType);
                        Debug.Assert(weapon != null);

                        Setting setting = weapon.Access(weaponSetting);
                        Debug.Assert(setting != null);

                        //Check value generator range (range check is not done at XML parsing-time for default values).
                        if (!valueGenerator.IsValueRangeWithinLimits(setting.Limits))
                        {
                            throw new Exception(String.Format("Generatable values for setting '{0}' must be within the range(s): {1}.",
                                                              setting.Name, setting.Limits.ToString()));
                        }

                        setting.SetValue(valueGenerator.GenerateValue(rng), valueGenerator);
                    }
                }
            }

            //Generate values for every extended option.
            if (version >= SchemeVersion.Armageddon3)
            {
                int optionsCount = Math.Min(scheme.ExtendedOptions.Length, _extendedOptionGenerators.Length);
                for (int i = 0; i < optionsCount; ++i)
                {
                    ValueGenerator valueGenerator = _extendedOptionGenerators[i];
                    if (valueGenerator != null)
                    {
                        ExtendedOptionTypes extendedOption = (ExtendedOptionTypes)i;
                        Setting             setting        = scheme.Access(extendedOption);
                        Debug.Assert(setting != null);

                        setting.SetValue(valueGenerator.GenerateValue(rng), valueGenerator);
                    }
                }
            }

            //Handle guarantees.
            foreach (Guarantee guarantee in _guarantees)
            {
                guarantee.ApplyGuarantee(scheme, rng);
            }

            return(scheme);
        }
 public void PickupWeapon(Weapon weapon)    //Overload for picking up a specified weapon
 {
     m_Weapon = weapon;
     m_Weapon.PickUp(m_WeaponAnchor);
     SetActionDistance();
 }
Example #36
0
 public ItemClass(Weapon type)
 {
     this.Type = 2;
     this.Id   = (int)type;
 }
Example #37
0
    // Update is called once per frame
    void Update()
    {
        int handToPick = 0;//1=Left; 2=Right

        if (Input.GetKeyDown(KeyCode.JoystickButton4))
        {
            handToPick = 1;
        }
        else if (Input.GetKeyDown(KeyCode.JoystickButton5))
        {
            handToPick = 2;
        }
        //get the weapon
        if (isLootNearby && (handToPick > 0) && currentLoot != null)
        {
            //check if we already have the weapon and show it
            //bool HasAlreadyWeapon = false;

            //check if looting give a weapon
            if (currentLoot.Item.GiveWeapon)
            {
                Debug.Log(currentLoot.Item.WeaponName.ToString());
                //give the right weapon
                foreach (Weapon weaponInManager in gameManager.WeaponList)
                {
                    if (currentLoot.Item.WeaponName.ToString() == weaponInManager.WeaponName.ToString())
                    {
                        if (handToPick == 1)
                        {
                            if (player.leftWeapon.Name != "")
                            {
                                string     tempName = player.leftWeapon.WeaponName.ToString();
                                GameObject itemObj  = Instantiate(gameManager.GetItemObj(tempName), transform.position, Quaternion.Euler(0, 0, 0));
                                itemObj.transform.localScale = WeaponSizeUp * itemObj.transform.localScale;
                                if (NextScene.nowName == "2_1" || NextScene.nowName == "2_2" || NextScene.nowName == "3_1" || NextScene.nowName == "3_2")
                                {
                                    itemObj.transform.localScale = new Vector3(4, 4, 4);
                                }
                                var worldCanvas = GameObject.Find("worldCanvas").transform;
                                itemObj.transform.parent = worldCanvas;
                            }
                            //get a copy of this weapon
                            Weapon newWeapon = CopyWeapon(weaponInManager);

                            //new weapon is already recharge
                            newWeapon.CurrentAmmos = newWeapon.AmmoSize;

                            //found the weapon, add it for the player
                            player.leftWeapon = newWeapon;
                            //Debug.Log(newWeapon.WeaponName);
                            RefreshWeaponUI(1);
                            ChangeWeapon(1, currentLoot.Item.WeaponName);
                        }

                        else if (handToPick == 2)
                        {
                            if (player.rightWeapon.Name != "")
                            {
                                string     tempName = player.rightWeapon.WeaponName.ToString();
                                GameObject itemObj  = gameManager.GetItemObj(tempName);
                                itemObj = Instantiate(gameManager.GetItemObj(tempName), transform.position, Quaternion.Euler(0, 0, 0));
                                itemObj.transform.localScale = WeaponSizeUp * itemObj.transform.localScale;
                                if (NextScene.nowName == "2_1" || NextScene.nowName == "2_2" || NextScene.nowName == "3_1" || NextScene.nowName == "3_2")
                                {
                                    itemObj.transform.localScale = new Vector3(4, 4, 4);
                                }
                                var worldCanvas = GameObject.Find("worldCanvas").transform;
                                itemObj.transform.parent = worldCanvas;
                            }
                            //get a copy of this weapon
                            Weapon newWeapon = CopyWeapon(weaponInManager);

                            //new weapon is already recharge
                            newWeapon.CurrentAmmos = newWeapon.AmmoSize;

                            //found the weapon, add it for the player
                            player.rightWeapon = newWeapon;
                            RefreshWeaponUI(2);
                            ChangeWeapon(2, currentLoot.Item.WeaponName);
                        }
                        handToPick = 0;
                    }
                }

                //destroy loot
                GameObject.Destroy(currentLoot.gameObject);
                //clear loot
                currentLoot = null;
            }
        }

        //get the item
        if (isLootNearby && Input.GetKeyDown(KeyCode.Joystick1Button1) && currentLoot != null)//button B on controller
        {
            if (!currentLoot.Item.GiveWeapon)
            {
                if (currentLoot.Item.Name == "PurpleCrystal")
                {
                    player.Power += 20;
                }
                else if (currentLoot.Item.Name == "RedCrystal")
                {
                    player.Power += 10;
                }
                //destroy loot
                GameObject.Destroy(currentLoot.gameObject);
                //clear loot
                currentLoot = null;
            }
        }
    }
Example #38
0
        public void CheckMeleeWeaponDamage(Weapon weapon, string weaponsDamage, bool TwoWeaponFighting, bool BiteAttack, int weaponCount, int weaponIndex,
                                           string Size, AbilityScores.AbilityScores _abilityScores, MonSBSearch _monSBSearch, StatBlockMessageWrapper _messageXML, int FighterLevel, int ACDefendingMod, bool MagicWeapon, bool GreaterMagicWeapon, IndividualStatBlock_Combat _indvSB)
        {
            string formula        = string.Empty;
            bool   SizeDifference = false;


            StatBlockInfo.SizeCategories MonSize    = StatBlockInfo.GetSizeEnum(Size);
            StatBlockInfo.SizeCategories WeaponSize = weapon.WeaponSize;
            if (MonSize != WeaponSize)
            {
                SizeDifference = true;
            }

            if (_monSBSearch.HasSQ("undersized weapons"))
            {
                MonSize = StatBlockInfo.ReduceSize(MonSize);
            }

            StatBlockInfo.HDBlockInfo  damageComputed = new StatBlockInfo.HDBlockInfo();
            ShieldSpecialAbilitiesEnum shieldSA       = weapon.ShieldSpecialAbilities.ShieldSpecialAbilityValues;

            bool ShieldBashBoost = false;

            if ((shieldSA & ShieldSpecialAbilitiesEnum.Bashing) == ShieldSpecialAbilitiesEnum.Bashing)
            {
                ShieldBashBoost = true;
                MonSize         = StatBlockInfo.IncreaseSize(MonSize);
                MonSize         = StatBlockInfo.IncreaseSize(MonSize);
            }

            bool   HasNewWeaponDamge = false;
            Weapon weaponDamage      = null;

            if (weapon.search_name.ToLower() == "halfling sling staff")
            {
                weaponDamage      = Weapon.GetWeaponByName("club");
                HasNewWeaponDamge = true;
            }


            weaponsDamage = weaponsDamage.Replace("(", string.Empty);
            weaponsDamage = weaponsDamage.Replace(")", string.Empty);
            weaponsDamage = weaponsDamage.Replace("nonlethal", string.Empty);
            int    Pos        = weaponsDamage.IndexOf("/");
            string weaponCrit = string.Empty;

            if (Pos >= 0)
            {
                weaponCrit    = weaponsDamage.Substring(Pos + 1);
                weaponsDamage = weaponsDamage.Substring(0, Pos);
            }
            StatBlockInfo.HDBlockInfo damageSB = new StatBlockInfo.HDBlockInfo();
            if (weaponsDamage.Contains("|"))
            {
                Pos           = weaponsDamage.IndexOf("|");
                weaponsDamage = weaponsDamage.Substring(0, Pos);
            }
            damageSB.ParseHDBlock(weaponsDamage.Trim());

            if (weapon.@double)
            {
                //for double weapons assume the damage in the string is one of the ends
                if (weapon.damage_medium.Contains(damageSB.HDType.ToString()))
                {
                    weapon.damage_medium = damageSB.Multiplier.ToString() + damageSB.HDType.ToString();
                }

                if (weapon.damage_small.Contains(damageSB.HDType.ToString()))
                {
                    weapon.damage_small = damageSB.Multiplier.ToString() + damageSB.HDType.ToString();
                }
            }

            if (MonSize == StatBlockInfo.SizeCategories.Medium && !ShieldBashBoost && !SizeDifference)
            {
                if (HasNewWeaponDamge)
                {
                    damageComputed.ParseHDBlock(weapon.damage_medium);
                }
                else
                {
                    damageComputed.ParseHDBlock(weapon.damage_medium);
                }
            }
            else if (MonSize == StatBlockInfo.SizeCategories.Small && !ShieldBashBoost && !SizeDifference)
            {
                if (HasNewWeaponDamge)
                {
                    damageComputed.ParseHDBlock(weapon.damage_small);
                }
                else
                {
                    damageComputed.ParseHDBlock(weapon.damage_small);
                }
            }
            else if (!SizeDifference)
            {
                if (HasNewWeaponDamge)
                {
                    damageComputed.ParseHDBlock(StatBlockInfo.ChangeWeaponDamageSize(weaponDamage.damage_medium, MonSize));
                }
                else
                {
                    damageComputed.ParseHDBlock(StatBlockInfo.ChangeWeaponDamageSize(weapon.damage_medium, MonSize));
                }
            }
            else
            {
                //SizeDifference = true
                if (MonSize == StatBlockInfo.SizeCategories.Small)
                {
                    damageComputed.ParseHDBlock(weapon.damage_small);
                }
                else
                {
                    StatBlockInfo.SizeCategories tempSize = StatBlockInfo.SizeCategories.Medium;
                    if (WeaponSize == tempSize)
                    {
                        tempSize = MonSize;
                    }
                    damageComputed.ParseHDBlock(StatBlockInfo.ChangeWeaponDamageSize(weapon.damage_medium, tempSize));
                }
            }

            double StrBonus;
            bool   OneHandedAsTwo;
            string ModUsed = ComputeStrBonus(weapon, TwoWeaponFighting, BiteAttack, weaponCount, weaponIndex, _monSBSearch, _abilityScores, out StrBonus, out OneHandedAsTwo);

            formula += " +" + StrBonus.ToString() + " " + ModUsed + " Bonus Used";
            damageComputed.Modifier += Convert.ToInt32(StrBonus);

            if (weapon.WeaponSpecialMaterial == WeaponSpecialMaterials.AlchemicalSilver && (weapon.slashing || weapon.piercing))
            {
                damageComputed.Modifier--;
                formula += " -1 Alchemical Silver";
            }

            if (_monSBSearch.HasSQ("hulking changeling"))
            {
                damageComputed.Modifier++;
                formula += " +1 hulking changeling";
            }

            string hold2 = null;

            if (weapon.NamedWeapon)
            {
                hold2 = weapon.BaseWeaponName;
            }
            else
            {
                hold2 = weapon.search_name;
            }

            if (_monSBSearch.HasSpecialAttackGeneral("weapon training"))
            {
                damageComputed.Modifier += _monSBSearch.GetWeaponsTrainingModifier(hold2, ref formula);
            }

            damageComputed.Modifier += PoleArmTraingMods(weapon, _monSBSearch, FighterLevel, ref formula);

            bool ignoreEnhancement = false;

            if (weapon.name.ToLower() == "unarmed strike")
            {
                damageComputed.Modifier += _monSBSearch.GetOnGoingStatBlockModValue(OnGoingStatBlockModifier.StatBlockModifierTypes.NaturalDamage,
                                                                                    OnGoingStatBlockModifier.StatBlockModifierSubTypes.None, ref formula);
            }
            else
            {
                WeaponCommon weaponCommon = new WeaponCommon(magicInEffect, Weapons, _indvSB, _messageXML, _monSBSearch, _characterClasses, RaceName, DontUseRacialHD, RaceBaseType, HasRaceBase, RacialHDValue);

                weaponCommon.GetOnGoingDamageMods(MagicWeapon, GreaterMagicWeapon, _indvSB, ref formula, ref damageComputed, ref ignoreEnhancement);
            }

            if ((weapon.WeaponSpecialAbilities.WeaponSpecialAbilitiesValue & WeaponSpecialAbilitiesEnum.Furious) == WeaponSpecialAbilitiesEnum.Furious)
            {
                damageComputed.Modifier += 2;
                formula += " +1 furious";
            }

            string hold = null;

            if (weapon.NamedWeapon)
            {
                hold = weapon.BaseWeaponName.ToLower();
            }
            else
            {
                hold = weapon.search_name.ToLower();
            }

            if (hold.Contains("aldori"))
            {
                hold = hold.Replace("aldori", "Aldori");
            }

            if (_characterClasses.HasClass("aldori swordlord"))
            {
                if (hold.Contains("dueling sword"))
                {
                    int tenpMod = _monSBSearch.GetAbilityMod(AbilityScores.AbilityScores.AbilityName.Dexterity);
                    formula += " +" + tenpMod.ToString() + " Deft Strike";
                    damageComputed.Modifier += tenpMod;
                }
            }

            if (_monSBSearch.HasFeat("Weapon Specialization (" + hold + ")"))
            {
                formula += " +2 Weapon Specialization";
                damageComputed.Modifier += 2;
            }

            if (_monSBSearch.HasFeat("Greater Weapon Specialization (" + hold + ")"))
            {
                formula += " +2 Greater Weapon Specialization";
                damageComputed.Modifier += 2;
            }

            if (_monSBSearch.HasTemplate("graveknight"))
            {
                damageComputed.Modifier += 2;
                formula += " +2 Sacrilegious Aura";
            }

            if (_monSBSearch.HasFeat("Shield Master") && weapon.name.Contains("shield"))
            {
                formula += " +" + weapon.EnhancementBonus + " Shield Master";
                damageComputed.Modifier += weapon.EnhancementBonus;
            }

            //no enchantment bonus for shield bash
            if (weapon.EnhancementBonus > 0 && ACDefendingMod == 0 && !weapon.name.Contains("shield") && !ignoreEnhancement)
            {
                formula += " +" + weapon.EnhancementBonus.ToString() + " Enhancement Bonus";
                damageComputed.Modifier += weapon.EnhancementBonus;
            }

            if (weapon.Broken)
            {
                formula += " -2 Broken";
                damageComputed.Modifier -= 2;
            }



            if (damageSB.Equals(damageComputed))
            {
                _messageXML.AddPass("Melee Attack Damage-" + weapon.Weapon_FullName(), formula);
            }
            else
            {
                int temp5 = damageComputed.Modifier - 1;

                if (OneHandedAsTwo && damageSB.Modifier == temp5 && !_monSBSearch.HasShield()) // not all SB use two handed weapons; not error, their choice
                {
                    _messageXML.AddInfo(weapon.Weapon_FullName() + " could be used two-handed for extra damage");
                    _messageXML.AddPass("Melee Attack Damage-" + weapon.Weapon_FullName());
                }
                else
                {
                    _messageXML.AddFail("Melee Attack Damage-" + weapon.Weapon_FullName(), damageComputed.ToString(), damageSB.ToString(), formula);
                    if (OneHandedAsTwo)
                    {
                        _messageXML.AddFail("Melee Attack Damage-", "Weapon could be used As Two-Handed?");
                    }
                }
            }
            string tempWeaponCrit = weapon.critical.Replace("/×2", string.Empty);

            tempWeaponCrit = tempWeaponCrit.Replace((char)(8211), Char.Parse("-"));
            //if (tempWeaponCrit == weaponCrit)
            //{
            //    _messageXML.AddPass("Melee Attack Critical- " + weapon.Weapon_FullName());
            //}
            //else
            //{
            //    _messageXML.AddFail("Melee Attack Critical- " + weapon.Weapon_FullName(), weapon.critical, weaponCrit);

            //}
        }
Example #39
0
        protected void createPart()
        {
            try
            {
                string filename = "";
                if (_templates[_stemp] is WeaponTemplate)
                {
                    WeaponTemplate twtemplate = (WeaponTemplate)_templates[_stemp];
                    filename = WizardUtils.PartFolder + "/" + _packstring[_spack] + "/Weapon/" + getDirectoryName(twtemplate.weaponCategory) + "/" + _partname + ".asset";
                }
                else
                {
                    filename = WizardUtils.PartFolder + "/" + _packstring[_spack] + "/" + getDirectoryName(_templates[_stemp].category) + "/" + _partname + ".asset";
                }

                string directory = Path.GetDirectoryName(filename);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                    AssetDatabase.Refresh();
                }

                if (File.Exists(filename))
                {
                    if (!EditorUtility.DisplayDialog("Replace Part", "the part you wish to create is already exist", "Replace", "Cancel"))
                    {
                        return;
                    }
                }

                Part tpart = _templates[_stemp] is WeaponTemplate?EditorUtils.LoadScriptable <Weapon>(filename) :
                                 EditorUtils.LoadScriptable <Part>(filename);

                //..category
                tpart.category = _templates[_stemp].category;
                //category..

                //..package
                tpart.packageName = getPackageName(filename);
                //package..

                //..bodytype
                tpart.supportedBody = new List <BodyType>();
                for (int i = 0; i < _bodyopt.Length; i++)
                {
                    if (_bodyopt[i])
                    {
                        tpart.supportedBody.Add(_bodytype[i]);
                    }
                }
                //bodytype..

                //..textures
                tpart.texture   = _texture;
                tpart.colorMask = _mask;
                //textures..

                //..sprites
                if (_texture != null && _templates[_stemp].category != PartCategory.SkinDetails) //..skin details doesn't need to be sliced
                {
                    string sourcepath = AssetDatabase.GetAssetPath(_templates[_stemp].texture);
                    string targetpath = AssetDatabase.GetAssetPath(_texture);
                    tpart.sprites = SpriteSlicerUtils.SliceSprite(sourcepath, targetpath, getExcludedSprite());
                }
                else
                {
                    tpart.sprites = new List <Sprite>();
                }
                //sprites..

                if (tpart is Weapon)
                {
                    WeaponTemplate twtemplate = (WeaponTemplate)_templates[_stemp];
                    Weapon         tweapon    = (Weapon)tpart;
                    tweapon.weaponCategory = twtemplate.weaponCategory;
                    tweapon.muzzlePosition = _muzzlepos;
                    EditorUtility.SetDirty(tweapon);
                }
                else
                {
                    EditorUtility.SetDirty(tpart);
                }

                if (PartList.Static != null)
                {
                    InspectorPartList.Refresh(PartList.Static);
                }

                Selection.activeObject = tpart;

                string message = "part '" + tpart.name + "' has successfully created";
                EditorUtility.DisplayDialog("Success", message, "OK");
            }
            catch (Exception e)
            {
                EditorUtility.DisplayDialog("Error", "error on creating part: " + e.ToString(), "OK");
            }
        }
Example #40
0
            public static void Prefix(Mech __instance, int originalHitLoc, ArmorLocation aLoc, Weapon weapon, ref float totalArmorDamage, ref float directStructureDamage)
            {
                var mechTags = __instance.GetTags();

                if (mechTags.Contains("BR_MQ_ArmourBaffleSystem") && ((ArmorLocation)originalHitLoc == ArmorLocation.LeftArm || (ArmorLocation)originalHitLoc == ArmorLocation.RightArm ||
                                                                      (ArmorLocation)originalHitLoc == ArmorLocation.LeftLeg || (ArmorLocation)originalHitLoc == ArmorLocation.RightLeg))
                {
                    totalArmorDamage      *= Core.Settings.ArmourBaffleFactor;
                    directStructureDamage *= Core.Settings.ArmourBaffleFactor;
                }
                if (mechTags.Contains("BR_MQ_CrabClaws") && ((ArmorLocation)originalHitLoc == ArmorLocation.LeftArm || (ArmorLocation)originalHitLoc == ArmorLocation.RightArm))
                {
                    totalArmorDamage      *= Core.Settings.CrabClawDamageFactor;
                    directStructureDamage *= Core.Settings.CrabClawDamageFactor;
                }
                if (__instance.GetPilot().pilotDef.PilotTags.Contains("PQ_pilot_elite") && __instance.weightClass == WeightClass.MEDIUM)
                {
                    var pips = __instance.EvasivePipsCurrent;
                    totalArmorDamage      *= 1 - pips * 0.05f;
                    directStructureDamage *= 1 - pips * 0.05f;
                }
                if (__instance.GetPilot().pilotDef.SkillGuts >= 5)
                {
                    float gutsBonus = (__instance.GetPilot().pilotDef.SkillGuts - 4) * 0.02f;
                    if (__instance.GetPilot().pilotDef.SkillGuts >= 10)
                    {
                        gutsBonus += 0.03f;
                    }
                    totalArmorDamage      *= 1 - gutsBonus;
                    directStructureDamage *= 1 - gutsBonus;
                }
            }
Example #41
0
    void Start()
    {
        weapon = GetComponent <Weapon>();

        StartCoroutine(Fire());
    }
Example #42
0
        public void CheckRangedWeaponDamage(Weapon weapon, string weaponsDamage, string size, AbilityScores.AbilityScores _abilityScores,
                                            MonSBSearch _monSBSearch, StatBlockMessageWrapper _messageXML, bool MagicWeapon, bool GreaterMagicWeapon, IndividualStatBlock_Combat _indvSB)
        {
            string formula = string.Empty;

            StatBlockInfo.SizeCategories MonSize = StatBlockInfo.GetSizeEnum(size);

            if (_monSBSearch.HasSQ("undersized weapons"))
            {
                MonSize = StatBlockInfo.ReduceSize(MonSize);
            }

            StatBlockInfo.HDBlockInfo damageComputed = new StatBlockInfo.HDBlockInfo();
            if (weapon.name == "Sling" && _monSBSearch.HasGear("stones"))
            {
                damageComputed.ParseHDBlock(weapon.damage_small);
            }
            else if (MonSize == StatBlockInfo.SizeCategories.Medium)
            {
                damageComputed.ParseHDBlock(weapon.damage_medium);
            }
            else if (MonSize == StatBlockInfo.SizeCategories.Small)
            {
                damageComputed.ParseHDBlock(weapon.damage_small);
            }
            else
            {
                damageComputed.ParseHDBlock(StatBlockInfo.ChangeWeaponDamageSize(weapon.damage_medium, MonSize));
            }

            if (!weaponsDamage.Contains("entangle"))
            {
                ComputeRangeMod(weapon, _abilityScores, _monSBSearch, _messageXML, ref formula, ref damageComputed);
            }

            if (_monSBSearch.HasSpecialAttackGeneral("weapon training"))
            {
                damageComputed.Modifier += _monSBSearch.GetWeaponsTrainingModifier(weapon.search_name, ref formula);
            }

            if (_monSBSearch.HasClassArchetype("crossbowman"))
            {
                int fighterLevel = _characterClasses.FindClassLevel("fighter");
                if (fighterLevel >= 3)
                {
                    int dexBonus = _abilityScores.DexMod / 2;
                    if (dexBonus <= 0)
                    {
                        dexBonus = 1;
                    }
                    damageComputed.Modifier += dexBonus;
                    formula += " +" + dexBonus.ToString() + " crossbowman deadshot";
                }

                if (fighterLevel >= 5)
                {
                    int tempBonus = 1;
                    if (fighterLevel >= 9)
                    {
                        tempBonus++;
                    }
                    if (fighterLevel >= 13)
                    {
                        tempBonus++;
                    }
                    if (fighterLevel >= 17)
                    {
                        tempBonus++;
                    }
                    damageComputed.Modifier += tempBonus;
                    formula += " +" + tempBonus.ToString() + " crossbowman crossbow expert";
                }
            }

            if (_monSBSearch.HasClassArchetype("archer"))
            {
                int fighterLevel = _characterClasses.FindClassLevel("fighter");

                if (fighterLevel >= 5)
                {
                    int tempBonus = 1;
                    if (fighterLevel >= 9)
                    {
                        tempBonus++;
                    }
                    if (fighterLevel >= 13)
                    {
                        tempBonus++;
                    }
                    if (fighterLevel >= 17)
                    {
                        tempBonus++;
                    }
                    damageComputed.Modifier += tempBonus;
                    formula += " +" + tempBonus.ToString() + " Expert Archer";
                }
            }

            string hold = null;

            if (weapon.NamedWeapon)
            {
                hold = weapon.BaseWeaponName.ToLower();
            }
            else
            {
                hold = weapon.search_name.ToLower();
            }

            if (_monSBSearch.HasFeat("Weapon Specialization (" + hold + ")"))
            {
                formula += " +2 Weapon Specialization";
                damageComputed.Modifier += 2;
            }

            if (_monSBSearch.HasFeat("Greater Weapon Specialization (" + hold + ")"))
            {
                formula += " +2 Greater Weapon Specialization";
                damageComputed.Modifier += 2;
            }

            if (weapon.WeaponSpecialMaterial == WeaponSpecialMaterials.AlchemicalSilver && (weapon.slashing || weapon.piercing))
            {
                damageComputed.Modifier--;
                formula += " -1 Alchemical Silver";
            }

            if (weapon.EnhancementBonus > 0)
            {
                damageComputed.Modifier += weapon.EnhancementBonus;
                formula += " +" + weapon.EnhancementBonus.ToString() + " Enhancement Bonus";
            }

            if (_abilityScores.StrMod != 0 && Utility.IsThrownWeapon(weapon.search_name.ToLower()))
            {
                int MeleeModUsed = _abilityScores.StrMod;

                if (_monSBSearch.HasDefensiveAbility("incorporeal"))
                {
                    MeleeModUsed = _abilityScores.DexMod;
                }
                formula += " +" + MeleeModUsed.ToString() + " Str Bonus Used- Thrown";
                damageComputed.Modifier += Convert.ToInt32(MeleeModUsed);
            }

            if (weapon.name.Contains("bow") && !weapon.name.ToLower().Contains("composite") && !weapon.name.ToLower().Contains("cross") && _abilityScores.StrMod < 0)
            {
                damageComputed.Modifier += _abilityScores.StrMod;
            }

            bool         ignoreEnhancement = false;
            WeaponCommon weaponCommon      = new WeaponCommon(magicInEffect, Weapons, _indvSB, _messageXML, _monSBSearch, _characterClasses, RaceName, DontUseRacialHD, RaceBaseType, HasRaceBase, RacialHDValue);

            weaponCommon.GetOnGoingDamageMods(MagicWeapon, GreaterMagicWeapon, _indvSB, ref formula, ref damageComputed, ref ignoreEnhancement);

            weaponsDamage = weaponsDamage.Replace("(", string.Empty);
            weaponsDamage = weaponsDamage.Replace(")", string.Empty);
            weaponsDamage = weaponsDamage.Replace("nonlethal", string.Empty);
            int    Pos        = weaponsDamage.IndexOf("/");
            string weaponCrit = string.Empty;

            if (Pos >= 0)
            {
                weaponCrit    = weaponsDamage.Substring(Pos + 1);
                weaponsDamage = weaponsDamage.Substring(0, Pos);
            }
            StatBlockInfo.HDBlockInfo damageSB = new StatBlockInfo.HDBlockInfo();
            damageSB.ParseHDBlock(weaponsDamage.Trim());

            if (weapon.name == "rock" && _monSBSearch.HasSpecialAttackGeneral("rock throwing"))
            {
                if (damageComputed.Modifier != (_abilityScores.StrMod * 1.5))
                {
                    _messageXML.AddFail("Ranged Attack Damage- Rock ", (_abilityScores.StrMod * 1.5).ToString(), damageComputed.Modifier.ToString());
                }
            }


            if (weapon.name == "bomb" && _characterClasses.HasClass("alchemist"))
            {
                damageComputed        = new StatBlockInfo.HDBlockInfo();
                damageComputed.HDType = StatBlockInfo.HitDiceCategories.d6;
                int alchemistLevel = _characterClasses.FindClassLevel("alchemist");
                damageComputed.Multiplier = ((alchemistLevel - 1) / 2) + 1;
                damageComputed.Modifier   = _abilityScores.IntMod;

                formula = "+" + _abilityScores.IntMod.ToString() + " Int mod";
            }

            if (damageSB.Equals(damageComputed))
            {
                _messageXML.AddPass("Ranged Attack Damage " + weapon.Weapon_FullName(), formula);
            }
            else
            {
                _messageXML.AddFail("Ranged Attack Damage " + weapon.Weapon_FullName(), damageComputed.ToString(), damageSB.ToString(), formula);
            }

            //string tempWeaponCrit = weapon.critical.Replace("/×2", string.Empty);
            //tempWeaponCrit = tempWeaponCrit.Replace((char)(8211), Char.Parse("-"));
            //if (tempWeaponCrit == weaponCrit)
            //{
            //    _messageXML.AddPass("Ranged Attack Critical- " + weapon.Weapon_FullName());
            //}
            //else
            //{
            //    _messageXML.AddFail("Ranged Attack Critical- " + weapon.Weapon_FullName(), weapon.critical, weaponCrit);

            //}
        }
Example #43
0
 public DamageBlob DealDamage(Weapon weapon)
 {
     return(new DamageBlob(weapon.DealDamage(StrengthBonus)));
 }
        private void btnUseWeapon_Click(object sender, EventArgs e)
        {
            // Get the currently selected weapon from the cboWeapons ComboBox
            Weapon currentWeapon = (Weapon)cboWeapons.SelectedItem;

            // Determine the amount of damage to do to the monster
            int damageToMonster = RandomNumberGenerator.NumberBetween(currentWeapon.MinimumDamage, currentWeapon.MaximumDamage);

            // Apply the damage to the monster's CurrentHitPoints
            _currentMonster.CurrentHitPoints -= damageToMonster;

            // Display message
            rtbMessages.Text += "You hit the " + _currentMonster.Name + " for " + damageToMonster.ToString() + " points." + Environment.NewLine;

            // Check if the monster is dead
            if (_currentMonster.CurrentHitPoints <= 0)
            {
                // Monster is dead
                rtbMessages.Text += Environment.NewLine;
                rtbMessages.Text += "You defeated the " + _currentMonster.Name + Environment.NewLine;

                // Give player experience points for killing the monster
                _player.ExperiencePoints += _currentMonster.RewardExperiencePoints;
                rtbMessages.Text         += "You receive " + _currentMonster.RewardExperiencePoints.ToString() + " experience points" + Environment.NewLine;

                // Give player gold for killing the monster
                _player.Gold     += _currentMonster.RewardGold;
                rtbMessages.Text += "You receive " + _currentMonster.RewardGold.ToString() + " gold" + Environment.NewLine;

                // Get random loot items from the monster
                List <InventoryItem> lootedItems = new List <InventoryItem>();

                // Add items to the lootedItems list, comparing a random number to the drop percentage
                foreach (LootItem lootItem in _currentMonster.LootTable)
                {
                    if (RandomNumberGenerator.NumberBetween(1, 100) <= lootItem.DropPercentage)
                    {
                        lootedItems.Add(new InventoryItem(lootItem.Details, 1));
                    }
                }

                // If no items were randomly selected, then add the default loot item(s).
                if (lootedItems.Count == 0)
                {
                    foreach (LootItem lootItem in _currentMonster.LootTable)
                    {
                        if (lootItem.IsDefaultItem)
                        {
                            lootedItems.Add(new InventoryItem(lootItem.Details, 1));
                        }
                    }
                }

                // Add the looted items to the player's inventory
                foreach (InventoryItem inventoryItem in lootedItems)
                {
                    _player.AddItemToInventory(inventoryItem.Details);

                    if (inventoryItem.Quantity == 1)
                    {
                        rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.Name + Environment.NewLine;
                    }
                    else
                    {
                        rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.NamePlural + Environment.NewLine;
                    }
                }

                // Refresh player information and inventory controls
                lblHitPoints.Text  = _player.CurrentHitPoints.ToString();
                lblGold.Text       = _player.Gold.ToString();
                lblExperience.Text = _player.ExperiencePoints.ToString();
                lblLevel.Text      = _player.Level.ToString();

                UpdateInventoryListInUI();
                UpdateWeaponListInUI();
                UpdatePotionListInUI();

                // Add a blank line to the messages box, just for appearance.
                rtbMessages.Text += Environment.NewLine;

                // Move player to current location (to heal player and create a new monster to fight)
                MoveTo(_player.CurrentLocation);
            }
            else
            {
                // Monster is still alive

                // Determine the amount of damage the monster does to the player
                int damageToPlayer = RandomNumberGenerator.NumberBetween(0, _currentMonster.MaximumDamage);

                // Display message
                rtbMessages.Text += "The " + _currentMonster.Name + " did " + damageToPlayer.ToString() + " points of damage." + Environment.NewLine;

                // Subtract damage from player
                _player.CurrentHitPoints -= damageToPlayer;

                // Refresh player data in UI
                lblHitPoints.Text = _player.CurrentHitPoints.ToString();

                if (_player.CurrentHitPoints <= 0)
                {
                    // Display message
                    rtbMessages.Text += "The " + _currentMonster.Name + " killed you." + Environment.NewLine;

                    // Move player to "Home"
                    MoveTo(World.LocationByID(World.LOCATION_ID_HOME));
                }
            }
        }
Example #45
0
 private void ActivateWeapon(Weapon weapon)
 {
     _weapons.ToList().ForEach(x => x.gameObject.SetActive(false));
     weapon.gameObject.SetActive(true);
     weapon.Holder = _player;
 }
Example #46
0
 private void Awake()
 {
     _weapon    = GetComponent <Weapon>();
     _chadistAI = GameObject.FindGameObjectWithTag("Chadist AI").GetComponent <ChadistAI>();
 }
 private void Awake()
 {
     // player = FindObjectOfType<Player>().gameObject;
     RB        = GetComponent <Rigidbody2D>();
     GetWeapon = GetComponentInParent <Weapon>();
 }
Example #48
0
 public void SetWeapon(Weapon newWeapon)
 {
     currentWeapon = newWeapon;
 }
        public async Task CreateAsync(Weapon weapon)
        {
            await _dbContext.Weapons.AddAsync(weapon);

            await _unitOfWork.CompleteAsync();
        }
Example #50
0
    /// <summary>
    /// Changes the weapon
    /// </summary>
    /// <param name="weapon"></param>
    void ChangeWeapon(Weapon weapon)
    {
        currentWeapon = weapon;

        waitTime = currentWeapon.delay;
    }
Example #51
0
 public static void GiveCommand(BasePlayer player, Weapon weapon, int ammo)
 {
     player.GiveWeapon(weapon, ammo);
 }
Example #52
0
 public override void Fight()
 {
     Console.WriteLine("The clone troop fights...");
     Weapon.UseWeapon();
 }
Example #53
0
        private void mnuNewCritter_Click(object sender, EventArgs e)
        {
            Character objCharacter = new Character();

            if (Directory.GetFiles(Path.Combine(Application.StartupPath, "settings"), "*.xml").Count() > 1)
            {
                frmSelectSetting frmPickSetting = new frmSelectSetting();
                frmPickSetting.ShowDialog(this);

                if (frmPickSetting.DialogResult == DialogResult.Cancel)
                {
                    return;
                }

                objCharacter.SettingsFile = frmPickSetting.SettingsFile;
            }
            else
            {
                string strSettingsFile = Directory.GetFiles(Path.Combine(Application.StartupPath, "settings"), "*.xml")[0];
                strSettingsFile           = strSettingsFile.Replace(Path.Combine(Application.StartupPath, "settings"), string.Empty);
                strSettingsFile           = strSettingsFile.Replace(Path.DirectorySeparatorChar, ' ').Trim();
                objCharacter.SettingsFile = strSettingsFile;
            }

            // Override the defaults for the setting.
            objCharacter.IgnoreRules = true;
            objCharacter.IsCritter   = true;
            objCharacter.BuildMethod = CharacterBuildMethod.Karma;
            objCharacter.BuildPoints = 0;

            // Make sure that Running Wild is one of the allowed source books since most of the Critter Powers come from this book.
            bool blnRunningWild = false;

            blnRunningWild = (objCharacter.Options.Books.Contains("RW"));

            if (!blnRunningWild)
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_Main_RunningWild"), LanguageManager.Instance.GetString("MessageTitle_Main_RunningWild"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Show the Metatype selection window.
            if (objCharacter.BuildMethod == CharacterBuildMethod.Priority)
            {
                frmPriorityMetatype frmSelectMetatype = new frmPriorityMetatype(objCharacter);
                frmSelectMetatype.XmlFile = "critters.xml";
                frmSelectMetatype.ShowDialog();

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }
            else
            {
                frmKarmaMetatype frmSelectMetatype = new frmKarmaMetatype(objCharacter);
                frmSelectMetatype.XmlFile = "critters.xml";
                frmSelectMetatype.ShowDialog();

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }

            // Add the Unarmed Attack Weapon to the character.
            try
            {
                XmlDocument objXmlDocument = XmlManager.Instance.Load("weapons.xml");
                XmlNode     objXmlWeapon   = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]");
                TreeNode    objDummy       = new TreeNode();
                Weapon      objWeapon      = new Weapon(objCharacter);
                objWeapon.Create(objXmlWeapon, objCharacter, objDummy, null, null, null);
                objCharacter.Weapons.Add(objWeapon);
            }
            catch
            {
            }

            frmCreate frmNewCharacter = new frmCreate(objCharacter);

            frmNewCharacter.MdiParent   = this;
            frmNewCharacter.WindowState = FormWindowState.Maximized;
            frmNewCharacter.Show();

            objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged;
        }
Example #54
0
    //the card has now finished its animation
    //if it doesn't need to aim anything, it will immediately move into the final step
    //if it does, it will put the card into an "aimingbattlecry" state and not move into the final step until the effect is aimed
    public void playHandCard(HandCard cardToPlay)
    {
        //if it's a minion, it has to pay attention to how the minions are being pushed out of the way and prepare to insert itself
        //into the board at the previewpos
        if (cardToPlay.card.type == "minion")
        {
            cardToPlay.posToAddAt = previewPos;


            //create the minion
            Minion newMinion = playerInput.controller.createMinion(cardToPlay.card, this);

            //hide some stuff that is visible by default
            newMinion.divineshield.enabled = false;
            newMinion.taunt.enabled        = false;

            //check if the new minion needs to aim something
            bool needToAim = newMinion.effect.getBattlecryTarget();


            if (needToAim)
            {
                //tell the card to aim its battlecry and link the new minion to it
                cardToPlay.aimingBattlecry    = true;
                cardToPlay.needToAimBattlecry = true;
                cardToPlay.representative     = newMinion;

                //make the new minion invisible so it does not appear until after the aiming
                newMinion.GetComponent <SpriteRenderer>().enabled = false;
                newMinion.aBox.enabled = false;
                newMinion.hBox.enabled = false;
                newMinion.aText.GetComponent <MeshRenderer>().enabled = false;
                newMinion.hText.GetComponent <MeshRenderer>().enabled = false;
                newMinion.GetComponent <BoxCollider2D>().enabled      = false;
            }
            else
            {
                //didn't need to aim, immediately finish
                completeSummon(cardToPlay, newMinion);
            }
        }
        else if (cardToPlay.card.type == "spell")
        {
            //similar to minion summoning, but no need to create a minion or make it invisible
            Spell newSpell  = playerInput.controller.createSpell(cardToPlay.card, this);
            bool  needToAim = newSpell.effect.getSpellTarget();

            if (needToAim)
            {
                cardToPlay.aimingBattlecry     = true;
                cardToPlay.needToAimBattlecry  = true;
                cardToPlay.spellRepresentative = newSpell;
            }
            else
            {
                completeSpellcast(cardToPlay, newSpell);
            }
        }
        else if (cardToPlay.card.type == "weapon")
        {
            Weapon newWeapon = playerInput.controller.createWeapon(cardToPlay.card, this);
            bool   needToAim = newWeapon.effect.getBattlecryTarget();
            if (needToAim)
            {
                //weapons with aimable effects will not be implemented
            }
            else
            {
                completeWeaponplay(cardToPlay, newWeapon);
            }
        }
    }
Example #55
0
 private void Awake()
 {
     ActiveWeapons = new Weapon[2];
     EquipRandomWeapon(0);
     EquipRandomWeapon(1);
 }
Example #56
0
        /// <summary>
        /// Create a new character and show the Create Form.
        /// </summary>
        private void ShowNewForm(object sender, EventArgs e)
        {
            Character objCharacter = new Character();

            if (Directory.GetFiles(Path.Combine(Application.StartupPath, "settings"), "*.xml").Count() > 1)
            {
                frmSelectSetting frmPickSetting = new frmSelectSetting();
                frmPickSetting.ShowDialog(this);

                if (frmPickSetting.DialogResult == DialogResult.Cancel)
                {
                    return;
                }

                objCharacter.SettingsFile = frmPickSetting.SettingsFile;
            }
            else
            {
                string strSettingsFile = Directory.GetFiles(Path.Combine(Application.StartupPath, "settings"), "*.xml")[0];
                strSettingsFile           = strSettingsFile.Replace(Path.Combine(Application.StartupPath, "settings"), string.Empty);
                strSettingsFile           = strSettingsFile.Replace(Path.DirectorySeparatorChar, ' ').Trim();
                objCharacter.SettingsFile = strSettingsFile;
            }

            // Show the BP selection window.
            frmSelectBP frmBP = new frmSelectBP(objCharacter);

            frmBP.ShowDialog();

            if (frmBP.DialogResult == DialogResult.Cancel)
            {
                return;
            }
            if (objCharacter.BuildMethod == CharacterBuildMethod.Karma)
            {
                frmKarmaMetatype frmSelectMetatype = new frmKarmaMetatype(objCharacter);
                frmSelectMetatype.ShowDialog();

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }
            // Show the Metatype selection window.
            else if (objCharacter.BuildMethod == CharacterBuildMethod.Priority)
            {
                frmPriorityMetatype frmSelectMetatype = new frmPriorityMetatype(objCharacter);
                frmSelectMetatype.ShowDialog();

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }
            else if (objCharacter.BuildMethod == CharacterBuildMethod.SumtoTen)
            {
                frmSumtoTenMetatype frmSumtoTenMetatype = new frmSumtoTenMetatype(objCharacter);
                frmSumtoTenMetatype.ShowDialog();

                if (frmSumtoTenMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }


            // Add the Unarmed Attack Weapon to the character.
            try
            {
                XmlDocument objXmlDocument = XmlManager.Instance.Load("weapons.xml");
                XmlNode     objXmlWeapon   = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]");
                TreeNode    objDummy       = new TreeNode();
                Weapon      objWeapon      = new Weapon(objCharacter);
                objWeapon.Create(objXmlWeapon, objCharacter, objDummy, null, null, null);
                objCharacter.Weapons.Add(objWeapon);
            }
            catch
            {
            }

            frmCreate frmNewCharacter = new frmCreate(objCharacter);

            frmNewCharacter.MdiParent   = this;
            frmNewCharacter.WindowState = FormWindowState.Maximized;
            frmNewCharacter.Show();

            objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged;
        }
Example #57
0
        public static void GeneralFighterAI(MainGameWindow main, bool SingleTurn, Player ai, Map map)
        {
            //TODO: Seperate code, which logs details from code which decides what to do
            Troop                troop          = ai.troop;
            var                  enemies        = ai.enemies;
            ActionPoint          actionPoints   = ai.actionPoints;
            MovementPoints       movementPoints = ai.movementPoints;
            DistanceGraphCreator distanceGraph  = new DistanceGraphCreator(ai, troop.Position.X, troop.Position.Y, map, true);
            Thread               path           = new Thread(distanceGraph.CreateGraph);

            path.Start();
            path.Join();

            int damageDealt = 0;
            int dodged      = 0;

            while (actionPoints.Value > 0)
            {
                Point playerPos = enemies[0].troop.Position;

                //If the weapon is ranged and empty first load the weapon
                if (troop.activeWeapon.Attacks() == 0 && troop.activeWeapon is RangedWeapon w)
                {
                    Ammo selectedAmmo = w.GetSelectedAmmo();
                    foreach (var ammo in w.Ammo)
                    {
                        if (selectedAmmo is null || selectedAmmo.damage.Value < ammo.damage.Value)
                        {
                            ammo.Select(w);
                            selectedAmmo = ammo;
                        }
                    }
                }

                //Check if it can attack player
                int playerDistance = AIUtility.Distance(playerPos, troop.Position);
                int attacks        = troop.activeWeapon.Attacks();
                if (playerDistance <= troop.activeWeapon.range && attacks > 0)
                {
                    //Attack
                    var(damage, killed, hit) = main.Attack(ai, enemies[0]);
                    damageDealt += damage;
                    if (!hit)
                    {
                        dodged++;
                    }

                    if (killed)
                    {
                        map.overlayObjects.Add(new OverlayText(enemies[0].troop.Position.X * MapCreator.fieldSize, enemies[0].troop.Position.Y * MapCreator.fieldSize, Color.Red, $"-{damageDealt}"));
                        main.PlayerDied($"You have been killed by {ai.Name}!");
                        break;
                    }
                    actionPoints.RawValue--;
                    troop.activeWeapon.UseWeapon(enemies[0], main);
                    continue;
                }
                else if (troop.weapons.Exists(t => t.range >= playerDistance && t.Attacks() > 0))
                {
                    //Change weapon
                    Weapon best = troop.weapons.FindAll(t => t.range >= playerDistance)
                                  .Aggregate((t1, t2) => t1.range > t2.range ? t1 : t2);
                    troop.activeWeapon = best;
                    continue;
                }

                //Generate map of left value
                double[,] movementCosts = new double[map.width, map.height];
                for (int x = 0; x <= movementCosts.GetUpperBound(0); x++)
                {
                    for (int y = 0; y <= movementCosts.GetUpperBound(1); y++)
                    {
                        movementCosts[x, y] = -1;
                    }
                }

                //Find closest field to player
                Point closestField = new Point(-1, -1);
                try
                {
                    closestField = AIUtility.FindClosestField(distanceGraph, playerPos, movementPoints.Value, map,
                                                              (List <(Point point, double cost, double height)> list) => {
                        list.Sort((o1, o2) => {
                            double diffCost   = o1.cost - o2.cost;
                            double heightDiff = o1.height - o2.height;
                            if (Math.Abs(diffCost) >= 1)     //assume that using the weapon costs 1 action point
                            {
                                return(diffCost < 0 ? -1 : 1);
                            }
                            else if (heightDiff != 0)
                            {
                                return(diffCost < 0 ? -1 : 1);
                            }
                            return(0);
                        });
                        return(list.First().point);
                    });
                }
Example #58
0
    private void Update()
    {
        if (!state.IsDead)
        {
            if (entity.IsOwner)
            {
                CurrentWeapon = weaponManager.CurrentWeapon;
                weaponGFX     = CurrentWeapon.WeaponGFX;
                Sway();

                if (CanShoot == false)
                {
                    TimerConstant--;

                    if (TimerConstant <= 0)
                    {
                        CanShoot      = true;
                        TimerConstant = CurrentWeapon.ResetTime * 2;

                        if (CurrentWeapon.Name == "RPG")
                        {
                            weaponManager.CurrentWeapon.transform.GetChild(1).gameObject.SetActive(true);
                        }
                    }
                }

                if (IsReloading == false)
                {
                    switch (CurrentWeapon.Type)
                    {
                    case "single_shot":
                        if (Input.GetMouseButtonDown(0))
                        {
                            if (CanShoot == true)
                            {
                                Shoot(CurrentWeapon.Type);
                                CanShoot = false;
                            }
                        }
                        break;

                    case "fully_automatic":
                        if (Input.GetMouseButton(0))
                        {
                            if (CanShoot == true)
                            {
                                Shoot(CurrentWeapon.Type);
                                CanShoot = false;
                            }
                        }
                        break;

                    case "shotgun":
                        if (Input.GetMouseButtonDown(0))
                        {
                            if (CanShoot == true)
                            {
                                Shoot(CurrentWeapon.Type, CurrentWeapon.ProjectileAmount, true);
                                CanShoot = false;
                            }
                        }
                        break;

                    case "bolt_action":
                        if (Input.GetMouseButtonDown(0))
                        {
                            if (CanShoot == true)
                            {
                                Shoot(CurrentWeapon.Type, CurrentWeapon.ProjectileAmount, true);
                                CanShoot = false;
                            }
                        }
                        break;

                    case "projectile":
                        if (Input.GetMouseButtonDown(0))
                        {
                            if (CanShoot == true)
                            {
                                ShootProjectile();
                                CanShoot = false;
                            }
                        }
                        break;
                    }
                }

                if (CurrentWeapon.HasCrosshair == false)
                {
                    GetComponent <GUImanager>().UnsetCrosshair();
                }

                if (CurrentWeapon.AmmunitionInMagazine <= 0)
                {
                    HasToReload = true;
                }

                if (CurrentWeapon.AmmunitionInMagazine > 0)
                {
                    HasToReload = false;
                }

                if (Input.GetKeyDown(KeyCode.R))
                {
                    if (CurrentWeapon.AmmunitionInMagazine != CurrentWeapon.MagazineCapacity)
                    {
                        StartCoroutine(Reload());
                    }
                }

                if (Input.GetMouseButton(1))
                {
                    Aim(1);
                }

                if (!Input.GetMouseButton(1))
                {
                    Aim(0);
                }
            }
        }
    }
Example #59
0
 public override void FireWeapon()
 {
     Weapon.FireWeapon();
 }
        private void btnUseWeapon_Click(object sender, EventArgs e)
        {
            Weapon currentWeapon = (Weapon)cboWeapons.SelectedItem;

            int damageToMonster = RandomNumberGenerator.NumberBetween(
                currentWeapon.MinimumDamage, currentWeapon.MaximumDamage);

            _currentMonster.CurrentHitPoints -= damageToMonster;

            rtbMessages.Text += "You hit the " + _currentMonster.Name + " for " +
                                damageToMonster.ToString() + " points." + Environment.NewLine;

            //Check if monster is dead
            if (_currentMonster.CurrentHitPoints <= 0)
            {
                //Is Dead
                rtbMessages.Text += Environment.NewLine;
                rtbMessages.Text += "You defeated the " + _currentMonster.Name +
                                    Environment.NewLine;

                //Give Experience
                _player.ExperiencePoints += _currentMonster.RewardExperiencePoints;
                rtbMessages.Text         += "You receive " +
                                            _currentMonster.RewardExperiencePoints.ToString() +
                                            " experience points" + Environment.NewLine;

                //Give player gold
                _player.Gold     += _currentMonster.RewardGold;
                rtbMessages.Text += "You recieve " +
                                    _currentMonster.RewardGold.ToString() + " gold" + Environment.NewLine;

                //Get random loot item
                List <InventoryItem> lootedItems = new List <InventoryItem>();

                foreach (LootItem lootItem in _currentMonster.LootTable)
                {
                    if (RandomNumberGenerator.NumberBetween(1, 100) <= lootItem.DropPercentage)
                    {
                        lootedItems.Add(new InventoryItem(lootItem.Details, 1));
                    }
                }

                if (lootedItems.Count == 0)
                {
                    foreach (LootItem lootItem in _currentMonster.LootTable)
                    {
                        if (lootItem.IsDefaultItem)
                        {
                            lootedItems.Add(new InventoryItem(lootItem.Details, 1));
                        }
                    }
                }

                foreach (InventoryItem inventoryItem in lootedItems)
                {
                    _player.AddItemToInventory(inventoryItem.Details);

                    if (inventoryItem.Quantity == 1)
                    {
                        rtbMessages.Text += "You loot " +
                                            inventoryItem.Quantity.ToString() + " " +
                                            inventoryItem.Details.Name + Environment.NewLine;
                    }
                    else
                    {
                        rtbMessages.Text += "You loot " +
                                            inventoryItem.Quantity.ToString() + " " +
                                            inventoryItem.Details.NamePlural + Environment.NewLine;
                    }
                }

                //Refresh player inventory info & controls
                lblHitPoints.Text  = _player.CurrentHitPoints.ToString();
                lblGold.Text       = _player.Gold.ToString();
                lblExperience.Text = _player.ExperiencePoints.ToString();
                lblLevel.Text      = _player.Level.ToString();

                UpdateInventoryListInUI();
                UpdateWeaponListInUI();
                UpdatePotionListInUI();

                //Blank line for space in message box
                rtbMessages.Text += Environment.NewLine;

                // Move player to current location (to heal player and create a new monster to fight)
                MoveTo(_player.CurrentLocation);
            }
            else
            {
                //Monster still alive. Monster monster attacks player.
                int damageToPlayer =
                    RandomNumberGenerator.NumberBetween(0, _currentMonster.MaximumDamage);

                rtbMessages.Text += "The " + _currentMonster.Name + " did " +
                                    damageToPlayer.ToString() + " points of damage." + Environment.NewLine;

                //If no damage message
                if (damageToPlayer == 0)
                {
                    rtbMessages.Text += "The " + _currentMonster.Name + " was too slow for you!! " +
                                        "You evaded the " + _currentMonster.Name + "'s attack!!" + Environment.NewLine;
                }

                //If hit subtract damage
                _player.CurrentHitPoints -= damageToPlayer;

                //Refresh UI
                lblHitPoints.Text = _player.CurrentHitPoints.ToString();

                //If player killed
                if (_player.CurrentHitPoints <= 0)
                {
                    rtbMessages.Text += "The " + _currentMonster.Name + " killed you." +
                                        Environment.NewLine;

                    MoveTo(World.LocationByID(World.LOCATION_ID_HOME));
                }
            }
        }