Search Unity

Accumulable strike

Discussion in 'Scripting' started by shoo, Jun 9, 2013.

  1. shoo

    shoo

    Joined:
    Nov 19, 2012
    Posts:
    67
    Hello! I'm absolutely new to Unity and i'm have a trouble! I wanna make time dependent strike with force incrementing by time of Fire1 button down. But also I need to track collisions through trigger attached to Empty object inserted in Player object(Player already has Collider for work with physics engine).
    I'm using Update on Trigger object for start accumulating force and then inrcease it:
    Code (csharp):
    1.  
    2.     void Update () {
    3.         if (Input.GetButtonDown("Fire1")) {
    4.             isStriking = true;
    5.         }
    6.         if (isStriking) {
    7.             if (strikeForce<maxStrikeForce) { strikeForce += 20f; }
    8.             Debug.Log(strikeForce);
    9.         }      
    10.  
    11.     }
    12.  
    But i'm need to strike only if collide detected therefore I process that in OnTriggerStay:
    Code (csharp):
    1.  
    2.     void OnTriggerStay(Collider collider) {
    3.         if (collider.gameObject.tag == "ball") {
    4.             collider.gameObject.renderer.material.color = Color.yellow;
    5.             if (Input.GetButtonUp("Fire1")) {
    6.                 collider.rigidbody.AddForce((collider.transform.position - transform.position) * strikeForce, ForceMode.Acceleration);
    7.                 isStriking = false;
    8.                 strikeForce = 0;
    9.             }
    10.         }
    11.     }
    12.  
    The problem is that I need to reset strikeForce not only when OnTriggerStay(force must be nulled each time OnButtonUp). When I reset it on Update, that has unpredictable behaviour and periodically script don't AddForce to collided object(becouse Update reset strikeForce earler than OnTriggerStay handle it, I think). How I can resolve this problem? And can there be a better solution for my problem? Thanks!
     
    Last edited: Jun 9, 2013