Tutorial: Melee Attack

Melee Attack tutorial

 

In this tutorial we will make the human female avatar be able to do melee attack using the “Action2” or the Number 2 Key. 

 

1.  To CasualHumanFemaleAvatar.cs

 

add to the beginning of the file:

 

using System.Collections.Generic;

using Microsoft.Xna.Framework;

using Visual3D.Commands;

 

 

2. Add the following:

 

        protected override void OnConstructPrototype()

        {

            float animSpeed = 1.2f * SpeedScalar;

 

            base.OnConstructPrototype();

 

 

            if (Animations.Count == 0) // once we start saving animations, this won't be needed anymore, even for prototypes.

            {

                AnimationSet.ConfigureAnimations(

                    new Animation(AvatarCommands.Action2, "attack2", animSpeed, null, false, false)

                    );

                AnimationSet.ConfigureAnimations(DefineCustomAnimations(animSpeed));

            }

 

            CommandSpec newChildren = new CommandSpec(AvatarCommands.LaunchMissile, new MethodCommand(Attack, null));

 

            AddCommand(newChildren);

            ReplaceCommand(new AutoFirePlusAnimationActivity(AvatarCommands.Action2, "AnimationFireWeapon", Attack));

 

 

 

        }

 

3.  Add the following:

 

 

        List<Avatar> _currentAttackTargets = new List<Avatar>(10);

 

        public void Attack(object args)

        {

 

            float maxDist2 = 10;// range* range;

 

            foreach (Avatar a in Avatars)

            {

 

                if (a == this)

 

                    continue;

 

                Vector3 targetOffset = a.WorldPosition - WorldPosition;

 

                float targetDist2 = targetOffset.LengthSquared();

 

 

 

                if (targetDist2 <= maxDist2)

                {

 

                    Quaternion thisOrientation = WorldOrientation;

 

                    Quaternion targetOrientation = a.WorldOrientation;

 

                    float angle = Quats.Angle(ref thisOrientation, ref targetOrientation);

 

                    if (angle < 315f || angle > 45f)

 

                        _currentAttackTargets.Add(a);

 

                }

 

            }

 

            foreach (Avatar target in _currentAttackTargets)

            {

 

                target.OnDamage(new Combat.DamagedEvent(this, target, 10));

 

            }

 

            _currentAttackTargets.Clear();

 

        }

 

4.  Build Solution and run Tech Demos.  I did this after building My First Tutorial that had both a female and male avatar.

 

5.  Move the female close to the male.  Press the “2” key.  See the male move away because it was attacked.

 

by Mike Hoisington, Tashi Duane