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.
Player Script Code (CSharp): using UnityEngine.SceneManagement; using UnityEngine; using System.Collections; public class KenjiPlayer : MonoBehaviour { // Variable declaration private Rigidbody2D KenjiRigidBody; private bool faceRight; private Animator KenjiAnimator; [SerializeField] // This allows you to access the value from Inspect or private float moveSpeed; //Player Attack private bool attack; private float attackTimer = 0; private float attackCd = 0.5f; public Collider2D attackTrigger; //Player Jump [SerializeField] private Transform[] groundPoints; [SerializeField] private float groundRadius; [SerializeField] private LayerMask whatIsGround; private bool isGrounded; private bool jump; public float jumpHeight; [SerializeField] private bool airControl; [SerializeField] private float jumpForce; [SerializeField] //Player Health private HPBarStat health; private bool allowJump = true; // Use this for initialization void Start() { // Make reference to the rigidbody attached to our character KenjiRigidBody = GetComponent<Rigidbody2D>(); // set faceRight to true; character face right by default faceRight = true; // Make reference to the animator attached to our character KenjiAnimator = GetComponent<Animator>(); } private void Awake() { health.Initialize(); } void Update() { // Check input on every frame userInput(); } // Update is called once per frame void FixedUpdate() { // Get input from user float horizontal = Input.GetAxis("Horizontal"); isGrounded = IsGrounded(); // Call function and pass a parameter moveKenji(horizontal); // flip player flipPlayer(horizontal); // Call function to attack KenjiAttacks(); KenjiLayers(); // Call function reset values resetValues(); } private void moveKenji(float horizontal) { if (isGrounded && jump) { KenjiRigidBody.AddForce (new Vector2 (0, jumpForce)); } if (!this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack") && (isGrounded || airControl)) { // Move the character based on the input KenjiRigidBody.velocity = new Vector2(horizontal * moveSpeed, KenjiRigidBody.velocity.y); } else { // Stop the character's move if attack is playing KenjiRigidBody.velocity = new Vector2(0, KenjiRigidBody.velocity.y); } KenjiAnimator.SetFloat("speed", Mathf.Abs(horizontal)); } private void flipPlayer(float horizontal) { if (horizontal > 0 && !faceRight || horizontal < 0 && faceRight) { faceRight = !faceRight; Vector3 charScale = transform.localScale; charScale.x *= -1; transform.localScale = charScale; } } private void KenjiAttacks() { if (attack && !this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack")) { KenjiAnimator.SetTrigger("attack"); KenjiRigidBody.velocity = Vector2.zero; attackTrigger.enabled = false; } } private void userInput() { if (Input.GetKeyDown(KeyCode.Space) && !this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack")) { attack = true; attackTimer = attackCd; attackTrigger.enabled = true; } if (attack) { if (attackTimer > 0) { attackTimer -= Time.deltaTime; } else { attack = false; attackTrigger.enabled = false; } } if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded==true && allowJump==true) { jump = true; allowJump = false; StartCoroutine (NoJump ()); } //Health if (Input.GetKeyDown(KeyCode.Q)) { health.CurrentVal -= 10; } if (Input.GetKeyDown(KeyCode.W)) { health.CurrentVal += 10; } } IEnumerator NoJump(){ yield return new WaitForSeconds (1f); allowJump = true; } private void resetValues() { attack = false; jump = false; } private bool IsGrounded() { if (KenjiRigidBody.velocity.y <= 0) foreach (Transform point in groundPoints) { // keep track of what we are colliding with Collider2D[] colliders = Physics2D.OverlapCircleAll (point.position, groundRadius, whatIsGround); for (int i = 0; i < colliders.Length; i++) { // if we are colliding with objects other than the character if (colliders [i].gameObject != gameObject) { return true; } } } return false; } private void KenjiLayers() { if (!isGrounded) { KenjiAnimator.SetLayerWeight(1, 1); } else { KenjiAnimator.SetLayerWeight(1, 0); } } } Code (CSharp): using UnityEngine.SceneManagement; using UnityEngine; using System.Collections; public class KenjiPlayer : MonoBehaviour { // Variable declaration private Rigidbody2D KenjiRigidBody; private bool faceRight; private Animator KenjiAnimator; [SerializeField] // This allows you to access the value from Inspect or private float moveSpeed; //Player Attack private bool attack; private float attackTimer = 0; private float attackCd = 0.5f; public Collider2D attackTrigger; //Player Jump [SerializeField] private Transform[] groundPoints; [SerializeField] private float groundRadius; [SerializeField] private LayerMask whatIsGround; private bool isGrounded; private bool jump; public float jumpHeight; [SerializeField] private bool airControl; [SerializeField] private float jumpForce; [SerializeField] //Player Health private HPBarStat health; private bool allowJump = true; // Use this for initialization void Start() { // Make reference to the rigidbody attached to our character KenjiRigidBody = GetComponent<Rigidbody2D>(); // set faceRight to true; character face right by default faceRight = true; // Make reference to the animator attached to our character KenjiAnimator = GetComponent<Animator>(); } private void Awake() { health.Initialize(); } void Update() { // Check input on every frame userInput(); } // Update is called once per frame void FixedUpdate() { // Get input from user float horizontal = Input.GetAxis("Horizontal"); isGrounded = IsGrounded(); // Call function and pass a parameter moveKenji(horizontal); // flip player flipPlayer(horizontal); // Call function to attack KenjiAttacks(); KenjiLayers(); // Call function reset values resetValues(); } private void moveKenji(float horizontal) { if (isGrounded && jump) { KenjiRigidBody.AddForce (new Vector2 (0, jumpForce)); } if (!this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack") && (isGrounded || airControl)) { // Move the character based on the input KenjiRigidBody.velocity = new Vector2(horizontal * moveSpeed, KenjiRigidBody.velocity.y); } else { // Stop the character's move if attack is playing KenjiRigidBody.velocity = new Vector2(0, KenjiRigidBody.velocity.y); } KenjiAnimator.SetFloat("speed", Mathf.Abs(horizontal)); } private void flipPlayer(float horizontal) { if (horizontal > 0 && !faceRight || horizontal < 0 && faceRight) { faceRight = !faceRight; Vector3 charScale = transform.localScale; charScale.x *= -1; transform.localScale = charScale; } } private void KenjiAttacks() { if (attack && !this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack")) { KenjiAnimator.SetTrigger("attack"); KenjiRigidBody.velocity = Vector2.zero; attackTrigger.enabled = false; } } private void userInput() { if (Input.GetKeyDown(KeyCode.Space) && !this.KenjiAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack")) { attack = true; attackTimer = attackCd; attackTrigger.enabled = true; } if (attack) { if (attackTimer > 0) { attackTimer -= Time.deltaTime; } else { attack = false; attackTrigger.enabled = false; } } if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded==true && allowJump==true) { jump = true; allowJump = false; StartCoroutine (NoJump ()); } //Health if (Input.GetKeyDown(KeyCode.Q)) { health.CurrentVal -= 10; } if (Input.GetKeyDown(KeyCode.W)) { health.CurrentVal += 10; } } IEnumerator NoJump(){ yield return new WaitForSeconds (1f); allowJump = true; } private void resetValues() { attack = false; jump = false; } private bool IsGrounded() { if (KenjiRigidBody.velocity.y <= 0) foreach (Transform point in groundPoints) { // keep track of what we are colliding with Collider2D[] colliders = Physics2D.OverlapCircleAll (point.position, groundRadius, whatIsGround); for (int i = 0; i < colliders.Length; i++) { // if we are colliding with objects other than the character if (colliders [i].gameObject != gameObject) { return true; } } } return false; } private void KenjiLayers() { if (!isGrounded) { KenjiAnimator.SetLayerWeight(1, 1); } else { KenjiAnimator.SetLayerWeight(1, 0); } } }
attackTrigger script Code (CSharp): using UnityEngine; using System.Collections; public class attackTrigger : MonoBehaviour { public int dmg = 20; void OnTriggerEnter2D(Collider2D col) { if (col.isTrigger != true & col.CompareTag("Monsters")) { col.SendMessageUpwards("Damage", dmg); } } }
Enemy Script Code (CSharp): using UnityEngine; using System.Collections; public class SlimeControl : MonoBehaviour { public LevelManager levelManager; public Transform[] patrolpoints; int currentPoint; public float speed = 0.5f; public float timestill = 2f; public float sight = 3f; public float force = 100; Animator anim; //Player Gain Money By Defeating The Enemies public int pointsToAdd; // Use this for initialization void Start() { anim = GetComponent<Animator>(); StartCoroutine("Patrol"); anim.SetBool("walking", true); } // Update is called once per frame void Update() { RaycastHit2D hit = Physics2D.Raycast (transform.position, transform.localScale.x * Vector2.right, sight); if (hit.collider != null && hit.collider.name == "Player") GetComponent<Rigidbody2D> ().AddForce (Vector3.up*force + (hit.collider.transform.position-transform.position)*force); } // Enemy Patrol IEnumerator Patrol() { while (true) { if (transform.position.x == patrolpoints[currentPoint].position.x) { currentPoint++; anim.SetBool("walking", false); yield return new WaitForSeconds(timestill); anim.SetBool("walking", true); } if (currentPoint >= patrolpoints.Length) { currentPoint = 0; } transform.position = Vector2.MoveTowards(transform.position, new Vector2(patrolpoints[currentPoint].position.x, transform.position.y), speed); if (transform.position.x < patrolpoints[currentPoint].position.x) transform.localScale = new Vector3(-1, 1, 1); else if (transform.position.x > patrolpoints[currentPoint].position.x) transform.localScale = Vector3.one; yield return null; } } // Enemy Target Player void OnTriggerEnter2D(Collider2D other) { //if (other.name == "Player") // Destroy (this.gameObject, 0.1f); if (other.GetComponent<KenjiPlayer>() == null) return; GainMoneyManager.AddPoints(pointsToAdd); //if (curHealth <= 0) Destroy(this.gameObject, 0.1f); } //Enemy Sight void OnDrawGizmos() { Gizmos.color = Color.red; Gizmos.DrawLine (transform.position,transform.position+transform.localScale.x * Vector3.left*sight); } //Damage output from Enemies //public void Damage(int damage) // { // curHealth -= damage; //gameObject.GetComponent<Animation>().Play("Player_Skills"); //} }
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"..
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
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.
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.