Unity3D: Adding charged force in relation to position

97 views Asked by At

I am trying to make a game which "kind of" simulates the shooting of the "worms" game. The player can choose the position (circular) of an object and then, the force that is applied to the object should move in the direction its pointing towards. I tried using the AddForce(transform.right) code, but it would just go to the right. (2D BoxCollider and RigidBody2D)

Then comes the hard part, making the player choose the force by charging the power. When the player holds down the "f" key, I want the power to go up to a certain point. Once it reaches that point, I want it to go down again and then up again, so the player can choose the power he wants. I have no idea how to go about this.

1

There are 1 answers

6
bill On BEST ANSWER

It's been awhile since I've did Unity coding, so there may be some minor errors with my syntax but it should give you an idea of how to accomplish this. Your best bet for the loop is to use a coroutine to not block the main thread.

in Update() check for 'on key down' for F and start this coroutine:

IEnumerator Cycle()  
{
 float max = 10.0f;
 float min = 1.0f;
 float interval = 0.5f;

  do 
   {             
     for(int i=min;i<max;i++)
     {
       PowerValue = i;
       yield return new waitforseconds(interval);
      if(!input.getkey(f))
          break;
     }
     for(int i=max;i>min;i--)
     {
       PowerValue = i;
       yield return new waitforseconds(interval);
       if(!input.getkey(f))
          break;
     }

   } while(input.getkey(f));
}

And back in update() use that powerValue with getKeyUp(f)

And here is PowerValue setup as a parameter that prevents code from setting the max and min outside of a 1 to 10 range (configurable)

private float powerValue = 1.0f;
public float PowerValue
{
get { return powerValue; }
set {
      if(value>10f)
         powerValue=10f;
      else if (value<1f)
         powerValue=1f;
      else
          powerValue=value;
    }
}