Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Juzziee · Oct 03, 2014 at 09:06 AM · c#collisionarray of gameobjects

Collision based on array of enemies

Hello all,

New to C# here, any programming language on that note. I am teaching myself C# by making a little game and found myself running into an issue. I have created an array of enemies at the beginning of my code, when a play collides with an enemy, the play is knocked back a short distance (Currently using around 8 force). This is working great when there is only a single enemy, however if add more the one enemy, it will base the collision script on what ever the highest enemy is within the array.

I am using loop that will looking for enemies in the array but can't seem to get this fixed. Any help would be most appreciated. Here is my script below;

 using UnityEngine;
 using System.Collections;
 
 public class Movement : MonoBehaviour 
 { 
     public float maxSpeed = 10f;    // Character movement speed.
     public bool grounded = false;     //is the Character grounded?
     public Transform groundCheck;     // Used for creating grounded 
     float groundRadius = 0.2f;        //
     public LayerMask whatIsGround;    // Marker to show where the ground is
     float jumpForce = 15f;            // Force for vertical velocity (jumping)
     float knockForce = 8f;            // Force which the character will be knocked on both axis        
     float travelTime = 0.1f;        // Timer to set how often the timer will check for grounded to reset velocity
     public float doubleJump = 1;    // Double jump limit
     bool movement = true;            // Disables movement during knockbacks
     public int enemyIndex = 0;             // Used to check array each from in a enemyIndex++
     Vector3 enemy_pos;
 
     private GameObject[] Enemy;
 
     void Start(){
         Enemy = GameObject.FindGameObjectsWithTag ("Enemy");    // Define what is Enemy using tag Enemy 
         enemy_pos = Enemy[enemyIndex].transform.position; // Define the position of the Enemy array
 
     }
 
 
     void Update(){
         enemyPosition ();
 
 
         grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);    // Checks for grounded        
 
         if (movement) {
 
         // Character Movement
         if (Input.GetKey (KeyCode.A)) {
             transform.position += Vector3.left * maxSpeed * Time.deltaTime;
         }
         if (Input.GetKey (KeyCode.D)) {
             transform.position += Vector3.right * maxSpeed * Time.deltaTime;
         }
         if (Input.GetKey (KeyCode.W)) {                
             transform.position += Vector3.up * maxSpeed * Time.deltaTime;
         }
         if (Input.GetKey (KeyCode.S)) {
             transform.position += Vector3.down * maxSpeed * Time.deltaTime;
         }
         }
 
         // Jumping 
         if (grounded && Input.GetButtonDown ("Jump")) {
             rigidbody2D.velocity = new Vector2 (0, jumpForce);
         }
 
         // Double jump
         if (!grounded && Input.GetButtonDown ("Jump") && doubleJump > 0) {
             rigidbody2D.velocity = Vector2.zero;
             rigidbody2D.velocity = new Vector2 (0, jumpForce);
             doubleJump = 0;
                 } else if (grounded == true) {        
                     doubleJump = 1;
                 }
     }
 
     void OnCollisionStay2D(Collision2D coll) {
         if (coll.gameObject.tag == "Enemy") {
         //    rigidbody2D.velocity = new Vector2 (-8, 8); -- Old Code
             rigidbody2D.velocity = (knockForce * (transform.position - enemy_pos));
             Debug.Log (knockForce * (transform.position - enemy_pos));
             StartCoroutine (knockBack (travelTime));
             movement = false;
 
         }
     
     }
 
     IEnumerator knockBack(float travelTime) {
         yield return new WaitForSeconds (travelTime);
         movement = true;
         if (!grounded) {
             StartCoroutine (knockBack (travelTime));
             movement = false;
         }
         if (grounded){
             rigidbody2D.velocity = Vector3.zero;
         }
     }
 
     void enemyPosition(){
         enemyIndex++;
         if (enemyIndex >= Enemy.Length);
         Debug.Log (Enemy.Length);
             enemyIndex = 0;
         }
 
 }
 


Please don't mind the pretty messy code. Will clean that up as I near the end of this particular script!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Juzziee · Oct 03, 2014 at 04:48 AM

For those who get lost like I did - I over complicated it. Resolve the issue with this.

     void OnCollisionStay2D(Collision2D coll) {
         if (coll.gameObject.tag == "Enemy") {
             rigidbody2D.velocity = (knockForce * (transform.position - coll.gameObject.transform.position));
             Debug.Log (knockForce * (transform.position - coll.gameObject.transform.position));
             StartCoroutine (knockBack (travelTime));
             movement = false;
 
         }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

2 People are following this question.

avatar image avatar image

Related Questions

Distribute terrain in zones 3 Answers

How can I check if the collider is in my array and get which gameobject it is from the array? 1 Answer

Multiple Cars not working 1 Answer

Collision on specific Frames 1 Answer

OnCollisionEnter for translating gameObjects? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges