Search Unity

Attack Script

Discussion in 'Scripting' started by dckb1991, Nov 16, 2017.

  1. dckb1991

    dckb1991

    Joined:
    Sep 29, 2017
    Posts:
    14
    Anyone how to trigger player to attack enemy? Shall I put box collider 2d on the player sword?
     
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    what do you think "attack the enemy" means? I normally walk up to the enemy and swing a club at it and sometimes kick at him.

    What this was trying to do way tell you that the question was to vague and info given to help you out.
     
  3. dckb1991

    dckb1991

    Joined:
    Sep 29, 2017
    Posts:
    14
    would u mind to read my scripts? I have some scripts for my players as well as the enemies
     
  4. dckb1991

    dckb1991

    Joined:
    Sep 29, 2017
    Posts:
    14
    Player Script

    Code (CSharp):
    1. using UnityEngine.SceneManagement;
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class KenjiPlayer : MonoBehaviour
    6. {
    7.  
    8.     // Variable declaration
    9.     private Rigidbody2D KenjiRigidBody;
    10.  
    11.     private bool faceRight;
    12.  
    13.     private Animator KenjiAnimator;
    14.  
    15.     [SerializeField] // This allows you to access the value from Inspect or
    16.     private float moveSpeed;
    17.  
    18.     //Player Attack
    19.     private bool attack;
    20.     private float attackTimer = 0;
    21.     private float attackCd = 0.5f;
    22.     public Collider2D attackTrigger;
    23.  
    24.     //Player Jump
    25.     [SerializeField]
    26.     private Transform[] groundPoints;
    27.  
    28.     [SerializeField]
    29.     private float groundRadius;
    30.  
    31.     [SerializeField]
    32.     private LayerMask whatIsGround;
    33.  
    34.     private bool isGrounded;
    35.  
    36.     private bool jump;
    37.  
    38.     public float jumpHeight;
    39.  
    40.     [SerializeField]
    41.     private bool airControl;
    42.  
    43.  
    44.     [SerializeField]
    45.     private float jumpForce;
    46.  
    47.     [SerializeField]
    48.     //Player Health
    49.     private HPBarStat health;
    50.  
    51.     private bool allowJump = true;
    52.  
    53.  
    54.     // Use this for initialization
    55.     void Start()
    56.     {
    57.         // Make reference to the rigidbody attached to our character
    58.         KenjiRigidBody = GetComponent<Rigidbody2D>();
    59.  
    60.         // set faceRight to true; character face right by default
    61.         faceRight = true;
    62.  
    63.         // Make reference to the animator attached to our character
    64.         KenjiAnimator = GetComponent<Animator>();
    65.  
    66.     }
    67.  
    68.     private void Awake()
    69.     {
    70.         health.Initialize();
    71.     }
    72.  
    73.     void Update()
    74.     {
    75.         // Check input on every frame
    76.         userInput();
    77.     }
    78.  
    79.  
    80.  
    81.     // Update is called once per frame
    82.     void FixedUpdate()
    83.     {
    84.  
    85.         // Get input from user
    86.         float horizontal = Input.GetAxis("Horizontal");
    87.  
    88.         isGrounded = IsGrounded();
    89.  
    90.         // Call function and pass a parameter
    91.         moveKenji(horizontal);
    92.  
    93.         // flip player
    94.         flipPlayer(horizontal);
    95.  
    96.         // Call function to attack
    97.         KenjiAttacks();
    98.  
    99.         KenjiLayers();
    100.  
    101.         // Call function reset values
    102.         resetValues();
    103.  
    104.  
    105.     }
    106.  
    107.  
    108.     private void moveKenji(float horizontal)
    109.     {
    110.  
    111.         if (isGrounded && jump) {
    112.  
    113.             KenjiRigidBody.AddForce (new Vector2 (0, jumpForce));
    114.  
    115.         }
    116.  
    117.  
    118.         if (!this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack") && (isGrounded || airControl))
    119.         {
    120.  
    121.             // Move the character based on the input
    122.             KenjiRigidBody.velocity = new Vector2(horizontal * moveSpeed, KenjiRigidBody.velocity.y);
    123.  
    124.         }
    125.  
    126.         else
    127.         {
    128.             // Stop the character's move if attack is playing
    129.             KenjiRigidBody.velocity = new Vector2(0, KenjiRigidBody.velocity.y);
    130.         }
    131.  
    132.         KenjiAnimator.SetFloat("speed", Mathf.Abs(horizontal));
    133.     }
    134.  
    135.  
    136.  
    137.     private void flipPlayer(float horizontal)
    138.     {
    139.         if (horizontal > 0 && !faceRight || horizontal < 0 && faceRight)
    140.         {
    141.             faceRight = !faceRight;
    142.             Vector3 charScale = transform.localScale;
    143.             charScale.x *= -1;
    144.             transform.localScale = charScale;
    145.         }
    146.     }
    147.  
    148.  
    149.     private void KenjiAttacks()
    150.     {
    151.         if (attack && !this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    152.         {
    153.             KenjiAnimator.SetTrigger("attack");
    154.             KenjiRigidBody.velocity = Vector2.zero;
    155.             attackTrigger.enabled = false;
    156.         }
    157.     }
    158.  
    159.  
    160.     private void userInput()
    161.     {
    162.         if (Input.GetKeyDown(KeyCode.Space) && !this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    163.         {
    164.  
    165.             attack = true;
    166.             attackTimer = attackCd;
    167.  
    168.             attackTrigger.enabled = true;
    169.         }
    170.  
    171.         if (attack)
    172.         {
    173.             if (attackTimer > 0)
    174.             {
    175.                 attackTimer -= Time.deltaTime;
    176.             }
    177.             else
    178.             {
    179.                 attack = false;
    180.                 attackTrigger.enabled = false;
    181.             }
    182.  
    183.         }
    184.  
    185.         if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded==true && allowJump==true)
    186.         {
    187.             jump = true;
    188.             allowJump = false;
    189.             StartCoroutine (NoJump ());
    190.         }
    191.  
    192.         //Health
    193.         if (Input.GetKeyDown(KeyCode.Q))
    194.         {
    195.             health.CurrentVal -= 10;
    196.         }
    197.  
    198.         if (Input.GetKeyDown(KeyCode.W))
    199.         {
    200.             health.CurrentVal += 10;
    201.         }
    202.  
    203.     }
    204.  
    205.     IEnumerator NoJump(){
    206.         yield return new WaitForSeconds (1f);
    207.         allowJump = true;
    208.     }
    209.  
    210.  
    211.     private void resetValues()
    212.     {
    213.         attack = false;
    214.         jump = false;
    215.     }
    216.  
    217.  
    218.     private bool IsGrounded()
    219.     {
    220.         if (KenjiRigidBody.velocity.y <= 0)
    221.  
    222.             foreach (Transform point in groundPoints)
    223.             {
    224.                 // keep track of what we are colliding with
    225.                 Collider2D[] colliders = Physics2D.OverlapCircleAll (point.position, groundRadius, whatIsGround);
    226.  
    227.                 for (int i = 0; i < colliders.Length; i++)
    228.                 {
    229.                     // if we are colliding with objects other than the character
    230.                     if (colliders [i].gameObject != gameObject)
    231.                     {
    232.                         return true;
    233.                     }
    234.                 }
    235.             }
    236.  
    237.         return false;
    238.  
    239.  
    240.     }
    241.     private void KenjiLayers()
    242.     {
    243.         if (!isGrounded)
    244.         {
    245.             KenjiAnimator.SetLayerWeight(1, 1);
    246.         }
    247.         else
    248.         {
    249.             KenjiAnimator.SetLayerWeight(1, 0);
    250.         }
    251.     }
    252.  
    253.  
    254.  
    255. }
    Code (CSharp):
    1. using UnityEngine.SceneManagement;
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class KenjiPlayer : MonoBehaviour
    6. {
    7.  
    8.     // Variable declaration
    9.     private Rigidbody2D KenjiRigidBody;
    10.  
    11.     private bool faceRight;
    12.  
    13.     private Animator KenjiAnimator;
    14.  
    15.     [SerializeField] // This allows you to access the value from Inspect or
    16.     private float moveSpeed;
    17.  
    18.     //Player Attack
    19.     private bool attack;
    20.     private float attackTimer = 0;
    21.     private float attackCd = 0.5f;
    22.     public Collider2D attackTrigger;
    23.  
    24.     //Player Jump
    25.     [SerializeField]
    26.     private Transform[] groundPoints;
    27.  
    28.     [SerializeField]
    29.     private float groundRadius;
    30.  
    31.     [SerializeField]
    32.     private LayerMask whatIsGround;
    33.  
    34.     private bool isGrounded;
    35.  
    36.     private bool jump;
    37.  
    38.     public float jumpHeight;
    39.  
    40.     [SerializeField]
    41.     private bool airControl;
    42.  
    43.  
    44.     [SerializeField]
    45.     private float jumpForce;
    46.  
    47.     [SerializeField]
    48.     //Player Health
    49.     private HPBarStat health;
    50.  
    51.     private bool allowJump = true;
    52.  
    53.  
    54.     // Use this for initialization
    55.     void Start()
    56.     {
    57.         // Make reference to the rigidbody attached to our character
    58.         KenjiRigidBody = GetComponent<Rigidbody2D>();
    59.  
    60.         // set faceRight to true; character face right by default
    61.         faceRight = true;
    62.  
    63.         // Make reference to the animator attached to our character
    64.         KenjiAnimator = GetComponent<Animator>();
    65.  
    66.     }
    67.  
    68.     private void Awake()
    69.     {
    70.         health.Initialize();
    71.     }
    72.  
    73.     void Update()
    74.     {
    75.         // Check input on every frame
    76.         userInput();
    77.     }
    78.  
    79.  
    80.  
    81.     // Update is called once per frame
    82.     void FixedUpdate()
    83.     {
    84.  
    85.         // Get input from user
    86.         float horizontal = Input.GetAxis("Horizontal");
    87.  
    88.         isGrounded = IsGrounded();
    89.  
    90.         // Call function and pass a parameter
    91.         moveKenji(horizontal);
    92.  
    93.         // flip player
    94.         flipPlayer(horizontal);
    95.  
    96.         // Call function to attack
    97.         KenjiAttacks();
    98.  
    99.         KenjiLayers();
    100.  
    101.         // Call function reset values
    102.         resetValues();
    103.  
    104.  
    105.     }
    106.  
    107.  
    108.     private void moveKenji(float horizontal)
    109.     {
    110.  
    111.         if (isGrounded && jump) {
    112.  
    113.             KenjiRigidBody.AddForce (new Vector2 (0, jumpForce));
    114.  
    115.         }
    116.  
    117.  
    118.         if (!this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack") && (isGrounded || airControl))
    119.         {
    120.  
    121.             // Move the character based on the input
    122.             KenjiRigidBody.velocity = new Vector2(horizontal * moveSpeed, KenjiRigidBody.velocity.y);
    123.  
    124.         }
    125.  
    126.         else
    127.         {
    128.             // Stop the character's move if attack is playing
    129.             KenjiRigidBody.velocity = new Vector2(0, KenjiRigidBody.velocity.y);
    130.         }
    131.  
    132.         KenjiAnimator.SetFloat("speed", Mathf.Abs(horizontal));
    133.     }
    134.  
    135.  
    136.  
    137.     private void flipPlayer(float horizontal)
    138.     {
    139.         if (horizontal > 0 && !faceRight || horizontal < 0 && faceRight)
    140.         {
    141.             faceRight = !faceRight;
    142.             Vector3 charScale = transform.localScale;
    143.             charScale.x *= -1;
    144.             transform.localScale = charScale;
    145.         }
    146.     }
    147.  
    148.  
    149.     private void KenjiAttacks()
    150.     {
    151.         if (attack && !this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    152.         {
    153.             KenjiAnimator.SetTrigger("attack");
    154.             KenjiRigidBody.velocity = Vector2.zero;
    155.             attackTrigger.enabled = false;
    156.         }
    157.     }
    158.  
    159.  
    160.     private void userInput()
    161.     {
    162.         if (Input.GetKeyDown(KeyCode.Space) && !this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    163.         {
    164.  
    165.             attack = true;
    166.             attackTimer = attackCd;
    167.  
    168.             attackTrigger.enabled = true;
    169.         }
    170.  
    171.         if (attack)
    172.         {
    173.             if (attackTimer > 0)
    174.             {
    175.                 attackTimer -= Time.deltaTime;
    176.             }
    177.             else
    178.             {
    179.                 attack = false;
    180.                 attackTrigger.enabled = false;
    181.             }
    182.  
    183.         }
    184.  
    185.         if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded==true && allowJump==true)
    186.         {
    187.             jump = true;
    188.             allowJump = false;
    189.             StartCoroutine (NoJump ());
    190.         }
    191.  
    192.         //Health
    193.         if (Input.GetKeyDown(KeyCode.Q))
    194.         {
    195.             health.CurrentVal -= 10;
    196.         }
    197.  
    198.         if (Input.GetKeyDown(KeyCode.W))
    199.         {
    200.             health.CurrentVal += 10;
    201.         }
    202.  
    203.     }
    204.  
    205.     IEnumerator NoJump(){
    206.         yield return new WaitForSeconds (1f);
    207.         allowJump = true;
    208.     }
    209.  
    210.  
    211.     private void resetValues()
    212.     {
    213.         attack = false;
    214.         jump = false;
    215.     }
    216.  
    217.  
    218.     private bool IsGrounded()
    219.     {
    220.         if (KenjiRigidBody.velocity.y <= 0)
    221.  
    222.             foreach (Transform point in groundPoints)
    223.             {
    224.                 // keep track of what we are colliding with
    225.                 Collider2D[] colliders = Physics2D.OverlapCircleAll (point.position, groundRadius, whatIsGround);
    226.  
    227.                 for (int i = 0; i < colliders.Length; i++)
    228.                 {
    229.                     // if we are colliding with objects other than the character
    230.                     if (colliders [i].gameObject != gameObject)
    231.                     {
    232.                         return true;
    233.                     }
    234.                 }
    235.             }
    236.  
    237.         return false;
    238.  
    239.  
    240.     }
    241.     private void KenjiLayers()
    242.     {
    243.         if (!isGrounded)
    244.         {
    245.             KenjiAnimator.SetLayerWeight(1, 1);
    246.         }
    247.         else
    248.         {
    249.             KenjiAnimator.SetLayerWeight(1, 0);
    250.         }
    251.     }
    252.  
    253.  
    254.  
    255. }
     
  5. dckb1991

    dckb1991

    Joined:
    Sep 29, 2017
    Posts:
    14
    attackTrigger script

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class attackTrigger : MonoBehaviour
    5. {
    6.     public int dmg = 20;
    7.  
    8.  
    9.     void OnTriggerEnter2D(Collider2D col)
    10.     {
    11.         if (col.isTrigger != true & col.CompareTag("Monsters"))
    12.         {
    13.             col.SendMessageUpwards("Damage", dmg);
    14.         }
    15.     }
    16.  
    17. }
    18.  
    19.  
    20.  
     
  6. dckb1991

    dckb1991

    Joined:
    Sep 29, 2017
    Posts:
    14
    Enemy Script

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class SlimeControl : MonoBehaviour
    5. {
    6.     public LevelManager levelManager;
    7.     public Transform[] patrolpoints;
    8.     int currentPoint;
    9.     public float speed = 0.5f;
    10.     public float timestill = 2f;
    11.     public float sight = 3f;
    12.     public float force = 100;
    13.    
    14.     Animator anim;
    15.  
    16.    
    17.  
    18.     //Player Gain Money By Defeating The Enemies
    19.     public int pointsToAdd;
    20.  
    21.  
    22.     // Use this for initialization
    23.     void Start()
    24.     {
    25.         anim = GetComponent<Animator>();
    26.         StartCoroutine("Patrol");
    27.         anim.SetBool("walking", true);
    28.  
    29.     }
    30.  
    31.     // Update is called once per frame
    32.     void Update() {
    33.    
    34.        RaycastHit2D hit = Physics2D.Raycast (transform.position, transform.localScale.x * Vector2.right, sight);
    35.        if (hit.collider != null && hit.collider.name == "Player")
    36.            GetComponent<Rigidbody2D> ().AddForce (Vector3.up*force + (hit.collider.transform.position-transform.position)*force);
    37.  
    38.      
    39.      
    40.     }
    41.  
    42.     // Enemy Patrol
    43.     IEnumerator Patrol()
    44.     {
    45.         while (true)
    46.         {
    47.             if (transform.position.x == patrolpoints[currentPoint].position.x)
    48.             {
    49.                 currentPoint++;
    50.                 anim.SetBool("walking", false);
    51.                 yield return new WaitForSeconds(timestill);
    52.                 anim.SetBool("walking", true);
    53.             }
    54.  
    55.             if (currentPoint >= patrolpoints.Length)
    56.             {
    57.                 currentPoint = 0;
    58.             }
    59.  
    60.             transform.position = Vector2.MoveTowards(transform.position, new Vector2(patrolpoints[currentPoint].position.x, transform.position.y), speed);
    61.  
    62.             if (transform.position.x < patrolpoints[currentPoint].position.x)
    63.                 transform.localScale = new Vector3(-1, 1, 1);
    64.             else if (transform.position.x > patrolpoints[currentPoint].position.x)
    65.                 transform.localScale = Vector3.one;
    66.  
    67.  
    68.             yield return null;
    69.  
    70.  
    71.         }
    72.  
    73.  
    74.     }
    75.  
    76.     // Enemy Target Player
    77.     void OnTriggerEnter2D(Collider2D other)
    78.     {
    79.         //if (other.name == "Player")
    80.            // Destroy (this.gameObject, 0.1f);
    81.  
    82.         if (other.GetComponent<KenjiPlayer>() == null)
    83.             return;
    84.  
    85.         GainMoneyManager.AddPoints(pointsToAdd);
    86.  
    87.         //if (curHealth <= 0)
    88.         Destroy(this.gameObject, 0.1f);
    89.  
    90.        
    91.     }
    92.  
    93.  
    94.     //Enemy Sight
    95.     void OnDrawGizmos()
    96.     {
    97.         Gizmos.color = Color.red;
    98.  
    99.         Gizmos.DrawLine (transform.position,transform.position+transform.localScale.x * Vector3.left*sight);
    100.  
    101.     }
    102.  
    103.  
    104.     //Damage output from Enemies
    105.     //public void Damage(int damage)
    106.    // {
    107.        // curHealth -= damage;
    108.         //gameObject.GetComponent<Animation>().Play("Player_Skills");
    109.      
    110.     //}
    111.  
    112.  
    113. }
     
  7. dckb1991

    dckb1991

    Joined:
    Sep 29, 2017
    Posts:
    14
    I want to make a simple swing attack on enemy
     
  8. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    A couple of ideas come to mind... I've never actually done this, but just speculating.
    1) when attacking "swinging" against a targetted enemy, the player faces the enemy -- and then, if within range, they hit them.
    2) almost the same, but without auto-facing... and determine if the player is within a certain (angle) range of the enemy, as well as distance (naturally) -- then, it's a hit.

    *I do not think everything has to be "I actually hit the enemy with my sword/club game object".. :)
     
    anycolourulike likes this.
  9. dckb1991

    dckb1991

    Joined:
    Sep 29, 2017
    Posts:
    14
    How come my enemy sight codes are not working....it cant detect my player.
    I'm really a beginner for unity, need help please. Urgent
     
  10. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    I am not seeing anything about "site" I see a patrol in your enemy.

    For a beginner enemy AI is pretty hard. Learning something a bit easier would be prudent.

    That being said, lets roll down some of the features that an Enemy AI should do.

    Idle, Patrol, Scan, Seek, Destroy, Return

    These are just basic thoughts behind what an enemy should do. If he is doing nothing, he is at idle, if he is on patrol, he moves through waypoints, either cycling or ping ponging. During both of these, he is Scanning. This is either Physics.OverlapSphere or by raycasting. Raycasting is more believable. Seek is basically once he has found a target, he should move into attack range, Destroy is the attacking and Return happens if he has destroyed, or lost the target. All these should be covered in something called a Finite State Machine. This will allow you to program actions based on events that happen.

    https://en.wikipedia.org/wiki/Finite-state_machine

    Patrol, seek and return should all be covered by path finding. Unity has this built in as NavMesh.

    https://docs.unity3d.com/ScriptReference/AI.NavMesh.html
    https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.html

    Once those are done, then you should be able to do the destroy. The checks for that are ranged vs melee weapons, both of which boil down to a ranged attack. (melee being like 1 unit distance, while ranged is more) If the enemy is within range (and possibly above minimum range if you use that) then he can make an attack. If the attack requires that he stand still, he needs to stop.
     
  11. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    This code does not do any detection. it's simply drawing a line so you the view can see a visual line. This line does not return any data to run a check on.
    you need to do a raycast or collider trigger to check if the enemy can see the player.