Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Flicking, Shooting, Throwing, Tossing, Lobbing, Slicing script.

Discussion in 'iOS and tvOS' started by JeremyK, Jun 2, 2011.

  1. JeremyK

    JeremyK

    Joined:
    May 6, 2010
    Posts:
    13
    Hi everyone,

    We've recently completed our first mini game using Unity for iOS. It was a basketball (think papertoss) like game where you had to throw the ball in certain buckets and score points.

    I remember when I was first getting started I had a bit of a hard time finding a way to flick stuff around.
    I'm a technical artist but even javascript was new to me, most of the technical things I do are in the various software programs we use.

    Anyway, I thought I'd share what ended up working for us. This script was adapted from others I found posted around here, so I'm not fully taking credit for any or all of this. I went through a variety of different versions and this one seemed to work best.

    Basically it reads a finger swipe, and instantiates and adds a force to a game object based on that finger swipe. It takes into account the amount of time you've had your finger on screen, the speed of the flick, and the direction of the flick. This is then translated into 3D terms when adding the force.

    In addition to sharing this, I'm really open to any stupid things I did in the code, ways to do it differently, etc., because I'm sure there are lots of newbie mistakes.

    Anyway, hopefully someone can find this useful. If it wasn't for the big community behind Unity I'd probably still be pulling my hair out trying to get something to work.

    Adios!

    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var touchStart : Vector2;
    5. var touchEnd : Vector2;
    6. var flickTime = 5;
    7. var flickLength = 0;
    8. var ballVelocity : float;
    9. var ballSpeed = 0;
    10. var worldAngle : Vector3;
    11. var ballPrefab : GameObject;
    12. private var GetVelocity = false;
    13. var whoosh : GameObject[];
    14. var comfortZone : float;
    15. var couldbeswipe : boolean;
    16. var startCountdownLength : float = 0.0f;
    17. var startTheTimer : boolean = false;
    18. static var globalGameStart : boolean = false;
    19. static var shootEnable : boolean = false;
    20. private var startGameTimer : float = 0.0f;
    21.  
    22. function Start () {
    23.     startTheTimer = true;
    24.     Time.timeScale = 1;
    25.         if ( Application.isEditor )
    26.         Time.fixedDeltaTime = 0.01;
    27.     }
    28.                
    29. function Update () {
    30.     if (startTheTimer) {
    31.         startGameTimer += Time.deltaTime;
    32.     }
    33.     if (startGameTimer > startCountdownLength){
    34.         globalGameStart = true;
    35.         shootEnable = true;
    36.         startTheTimer = false;
    37.         startGameTimer = 0;
    38.     }  
    39.    
    40.     if (shootEnable) {
    41.         Debug.Log ("enabled!");
    42.         if (Input.touchCount > 0) {
    43.             var touch = Input.touches[0];
    44.             switch (touch.phase) {
    45.                 case TouchPhase.Began:
    46.                     flickTime = 5;
    47.                     timeIncrease();
    48.                     couldbeswipe = true;
    49.                     GetVelocity = true;
    50.                     touchStart= touch.position;
    51.                     break;
    52.                 case TouchPhase.Moved:
    53.                     if (Mathf.Abs(touch.position.y - touchStart.y) < comfortZone) {
    54.                         couldbeswipe = false;
    55.                     }
    56.                     else {
    57.                         couldbeswipe = true;
    58.                     }
    59.                 case TouchPhase.Stationary:
    60.                     if (Mathf.Abs(touch.position.y - touchStart.y) < comfortZone) {
    61.                         couldbeswipe = false;
    62.                     }
    63.                     break;
    64.                 case TouchPhase.Ended:
    65.                     var swipeDist = (touch.position - touchStart).magnitude;
    66.                     if (couldbeswipe  swipeDist > comfortZone) {
    67.                         GetVelocity = false;
    68.                         touchEnd = touch.position;
    69.                         var ball = Instantiate(ballPrefab, Vector3(0,2.6,-11), Quaternion.identity) as GameObject;
    70.                         GetSpeed();
    71.                         GetAngle();
    72.                         ball.rigidbody.AddForce(Vector3((worldAngle.x * ballSpeed), (worldAngle.y * ballSpeed), (worldAngle.z * ballSpeed)));
    73.                         PlayWhoosh();
    74.                        
    75.                     }
    76.                 }
    77.                 if (GetVelocity) {
    78.                     flickTime++;
    79.                 }
    80.         }
    81.     }
    82.     if (!shootEnable){
    83.         Debug.Log("shot disabled!");
    84.     }
    85. }
    86.  
    87. function timeIncrease() {
    88.     if (GetVelocity) {
    89.         flickTime++;
    90.     }
    91. }
    92.  
    93. function GetSpeed() {
    94.     flickLength = 90;
    95.     if (flickTime > 0) {
    96.         ballVelocity = flickLength / (flickLength - flickTime);
    97.         }
    98.     ballSpeed = ballVelocity * 30;
    99.     ballSpeed = ballSpeed - (ballSpeed * 1.65);
    100.     if (ballSpeed <= -33){
    101.         ballSpeed = -33;
    102.     }
    103.     Debug.Log("flick was" + flickTime);
    104.     flickTime = 5;
    105. }
    106.  
    107. function GetAngle () {
    108.     worldAngle = camera.ScreenToWorldPoint(Vector3 (touchEnd.x, touchEnd.y + 800, ((camera.nearClipPlane - 100)*1.8)));
    109. }
    110.  
    111. function PlayWhoosh(){
    112.   var sound = Instantiate(whoosh[Random.Range(0,whoosh.length)],transform.position,transform.rotation) as GameObject;
    113.   Debug.Log("Whoosh!");
    114. }
    115.  
    116.  
    117.  
    118.  
    119.  
    120.  
    121.  
    122.  
    123.  
     
    xpath likes this.
  2. gholme4

    gholme4

    Joined:
    Apr 14, 2011
    Posts:
    3
    Thanks. I'll try this out
     
  3. J_P_

    J_P_

    Joined:
    Jan 9, 2010
    Posts:
    1,027
    Saving this, thanks :)
     
  4. Rush-Rage-Games

    Rush-Rage-Games

    Joined:
    Sep 9, 2010
    Posts:
    1,997
    Ya, I bookmarked it! Thanks Jeremy for the script!
     
  5. Hakimo

    Hakimo

    Joined:
    Apr 29, 2010
    Posts:
    316
    This is amazing! Thanks very much. I'm already playing around with the code, chucking balls to a wall. I like to ask some questions about the script. How does it work in general? I know I have to attach it to a camera to set the direction of the ball. I can just edit the worldangle but I'm not sure what the values in there are for.

    Also, what are these variables represent? Flick Time, Flick Length, Whoosh, Comfort Zone, Could be swipe, startcountdown length, and start the timer.

    This is a new one to me, but I never knew I can actually use a gameobject to represent sound. I've always declare my audio clips in scripts. Is there a main difference between the two? and I also had to set it to play when awake to active the sounds.

    Finally, I noticed that if I do circle gestures, the balls are thrown backwards? Try doing 2 circles and it might do the same. For the balls, it seems I can only click on the screen to throw but if I click at the top of the screen, the balls are still thrown at the middle. Is this where I have to adjust the comfort zone to change the position?

    Thanks again for the code.

    - Hakimo
     
  6. JeremyK

    JeremyK

    Joined:
    May 6, 2010
    Posts:
    13
    Hakimo - Thanks for checking it out. Let me start off by saying I am no code ninja, this should "kinda" work for anyone just by drag/dropping on a camera, but for accuracy and stuff you'll definitely have to tweak some values. I'm a newbie so I kinda just made it work for our game.

    The audio clip thing was an oops, because I was using a game object with sound attached to play our sounds. It ended up just being a gameobject with an audio clip attached, so you're right it's not necessary.

    Ok, on to the nitty gritty. I meant to write a nice post about this and comment all the code but I forgot. I can do that now.

    Flicktime represents the amount of time a finger has been touching the screen. I was originally using this measure speed of the throw. I ended up using it for the ballVelocity which then became the ballSpeed which then was multiplied by the world angle of the swipe to add the force to the ball. The longer your flicktime the longer the ball would go, because generally a longer touch meant a longer swipe. If the user ever just held their finger on the screen and only moved a bit, it would cancel out the touch as being a swipe.

    I did a lot of tests with users using the game, and almost consistently I realized that a FAST long swipe and a slow short swipe generally are still separated enough using the flicktime counter. No matter how fast you flicked, if you flicked the entire screen the flicktime generally fell between a small range. Same with small fast / slow swipes. Am I making any sense?

    whoosh was a random set of sounds I was playing for each time you flicked. in the inspector you can set a size for it, and attach however many game objects / audio clips you wanted and it would play a different random sound each time you swiped.

    comfort zone was my way of canceling touches as being swipes. if it wasnt more than a certain pixel amount, it wasnt a swipe, so don't throw a ball. everytime my players would hit the pause button it would launch balls. I was just too noob to find a better solution. It can still be useful though for other things, as with this script and without a comfort zone, a default touch can launch the ball a reasonable distance. I didn't want my users just touching the screen to get cheap points. adding the default size minimum forced them to swipe a bit.

    couldbeswipe was a way for me to tell while switching through the various touch phases if the touch was still a swipe. at certain times, (stationary, slow moves, etc) it might be set to false, canceling the swipe. in the end, if couldbeswipe was true, it would process the other routines to actually instantiate the ball and play the sounds, etc.

    my game was a basketball type of shooter. you had ~30 seconds (or however long you wanted) to shoot as many balls into as many buckets as possible. when the game level launched though, i used a 4 second countdown (paired with on screen gfx) to show that the game was starting. similar to a race car game at the starting line.

    basically it says, on awake start the timer and output that value to startGameTimer. then, once startGameTimer was greater than startCountdownLength, the game had started. startCountdownLength is a value you set to determine how long your "ready set go" time should be. you can set this in the inspector, and like I said I was using 4 seconds. once this happens, ive got a global variable set to true that activates other parameters in my score and game timer scripts. it also allows the shooting to even take place (shootEnable). in other scripts, and based on the gametimer, this is eventually set to false when time is up.

    and you are right of course, this needs to be attached to a camera to work.

    to adjust where it throws you need to fiddle with a few settings.
    the GetSpeed and GetAngle functions will help you out here. I had to add certain numbers (+800 to Y, -100 / 1.8 to Z, etc) to the fields to make my game work. I'd suggest playing around with those numbers. Also look into the GetSpeed function because eventually ballspeed is multiplied by the worldAngle in GetAngle. These 2 things together determine the force added to the ball. I can imagine drawing circles might throw a ball backwards when you are moving your finger in the opposite direction of "screen up"? Again, comfortzone only determines the pixel amount necessary for something to register as a flick.

    hope I answered a few of your questions. sorry for bad terminology, I'm not a coder by nature. id be happy to answer any more questions you have. :)

    jeremy
     
  7. zyndro

    zyndro

    Joined:
    Oct 19, 2010
    Posts:
    78
    awesome! thanks for sharing!
    i'll give it a try when i got home =D
     
  8. MichaelMartin_526

    MichaelMartin_526

    Joined:
    Oct 8, 2009
    Posts:
    24
    Managed to get it working, JeremyK this example is fab, thank you for sharing!
     
    Last edited: Jun 10, 2011
  9. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    Always good to see someone sharing code, but it looks a bit complex (because it has all your game specific code in it).

    EDIT: Plan to post a simple version here, but haven't had time yet.
     
    Last edited: Jun 8, 2011
  10. nebula2012

    nebula2012

    Joined:
    May 20, 2011
    Posts:
    9
    thanks for sharing .
     
  11. okimoki

    okimoki

    Joined:
    May 13, 2010
    Posts:
    116
    Arrrrgh!! Cant get this to work on my iPad!! Can somebody post a working test scene so i could see how this should be setup?
    As far as i understood this should be just attached to the camera and a ball connected to "ballprefab"??

    Thanks for help!
     
  12. sidhesh

    sidhesh

    Joined:
    Nov 6, 2012
    Posts:
    51
    what all components i need to add in order to see game running on my ipad/iphone..presently i am adding ball prefab and attaching above script to main camera......Is it right..? plz help
     
  13. sidhesh

    sidhesh

    Joined:
    Nov 6, 2012
    Posts:
    51
    plz help unity3d forum
     
  14. ansh93

    ansh93

    Joined:
    Jul 17, 2012
    Posts:
    24
    Can someone please explain me what are the values in the getAngle function
    values "800","100","1.8"
    What are they for. And why doesnt the object goes to the left side much even if I try too ??
     
  15. ansh93

    ansh93

    Joined:
    Jul 17, 2012
    Posts:
    24
    Can you please tell me why those values are used in getangle function ??
     
  16. _Max_

    _Max_

    Joined:
    Feb 21, 2013
    Posts:
    160
    Thanks for sharing this, I will try this tonight..I hope it will work.
    Old thread but really been looking for a decent flick script for my game.
     
  17. namekaw

    namekaw

    Joined:
    Jan 25, 2013
    Posts:
    1
    I have added this to my main camera then put a car as my gameobject but it does not work. Is there something else that I should be doing or does it only work for balls (cannot imagine it is)????
     
  18. Gruffy

    Gruffy

    Joined:
    Nov 3, 2012
    Posts:
    13
    Hey JeremyK,
    I was reading your post and thought I would add a C# version for those seeking it in that language also.
    I hope you don`t mind, but as it is an implementation of your script but in another language i thought it would probably be okay.

    Thanks again for the script, though this thread may benefit from a small usage tutorial - of which I haven`t currently got time to give and feel it would be better described by its original owner.

    Thanks for the original script, I think its great.

    As for optimizing the script a little, I have very quickly replaced your GameObject instantiation with a quick fire on an AudioClip that uses a compulsory AudioSource that will attach to the GameObject you apply this script to automatically.

    I`m sorry to all out there, I haven`t got time right now to flesh the comments out for readability.
    hopefully, it will make sense as its not too far from your original one JeremyK.
    Anyway, Thanks for reading .
    C# converted with slightly different audio approach Script below:
    Code (csharp):
    1.  
    2.  
    3. using UnityEngine;
    4. using System.Collections;
    5. //demand an adio source be placed on this component for use with the audio clip
    6. [RequireComponent(typeof(AudioSource))]
    7. public class FlickThrowTouch : MonoBehaviour
    8. {
    9.  
    10.     public Vector2 touchStart;
    11.     public Vector2 touchEnd;
    12.     public int flickTime = 5;
    13.     public int flickLength = 0;
    14.     public float ballVelocity = 0.0f;
    15.     public float ballSpeed = 0;
    16.     public Vector3 worldAngle;
    17.     public GameObject ballPrefab;
    18.  
    19.     private bool GetVelocity = false;
    20.     //public GameObject[] woosh; //no
    21.     public AudioClip ballAudio;  //yes
    22.     public float comfortZone = 0.0f;
    23.     public bool couldBeSwipe;
    24.     public float startCountdownLength = 0.0f;
    25.     public bool startTheTimer = false;
    26.     static bool globalGameStart = false;
    27.     static bool shootEnable = false;
    28.     private float startGameTimer = 0.0f;
    29.  
    30.     private AudioSource asParamsControl;
    31.    
    32.     void  Start ()
    33.     {
    34.         asParamsControl = this.gameObject.GetComponentInChildren<AudioSource>();
    35.         this.asParamsControl.playOnAwake = false;
    36.         this.asParamsControl.loop = false;
    37.         startTheTimer = true;
    38.         Time.timeScale = 1;
    39.         if ( Application.isEditor )
    40.         {
    41.             Time.fixedDeltaTime = 0.01f;
    42.         }
    43.     }
    44.    
    45.     void Update ()
    46.     {
    47.         if (startTheTimer)
    48.         {
    49.             startGameTimer += Time.deltaTime;
    50.         }
    51.         if (startGameTimer > startCountdownLength)
    52.         {
    53.             globalGameStart = true;
    54.             shootEnable = true;
    55.             startTheTimer = false;
    56.             startGameTimer = 0;
    57.         }  
    58.        
    59.         if (shootEnable)
    60.         {
    61.             Debug.Log ("enabled!");
    62.             if (Input.touchCount > 0)
    63.             {
    64.                 var touch = Input.touches[0];
    65.                 switch (touch.phase)
    66.                 {
    67.                 case TouchPhase.Began:
    68.                                     flickTime = 5;
    69.                                     timeIncrease();
    70.                                     couldBeSwipe = true;
    71.                                     GetVelocity = true;
    72.                                     touchStart= touch.position;
    73.                                     break;
    74.                 case TouchPhase.Moved:
    75.                                     if (Mathf.Abs(touch.position.y - touchStart.y) < comfortZone)
    76.                                     {
    77.                                         couldBeSwipe = false;
    78.                                     }
    79.                                     else
    80.                                     {
    81.                                         couldBeSwipe = true;
    82.                                     }
    83.                                     break;
    84.                 case TouchPhase.Stationary:
    85.                                     if (Mathf.Abs(touch.position.y - touchStart.y) < comfortZone)
    86.                                     {
    87.                                         couldBeSwipe = false;
    88.                                     }
    89.                                     break;
    90.                 case TouchPhase.Ended:
    91.                                     float swipeDist = (touch.position - touchStart).magnitude;
    92.                                     if (couldBeSwipe  swipeDist > comfortZone)
    93.                                     {
    94.                                         GetVelocity = false;
    95.                                         touchEnd = touch.position;
    96.                                         Rigidbody ball = Instantiate(ballPrefab, new Vector3(0.0f,2.6f,-11.0f), Quaternion.identity) as Rigidbody;
    97.                                         GetSpeed();
    98.                                         GetAngle();
    99.                                         ball.rigidbody.AddForce(new Vector3((worldAngle.x * ballSpeed), (worldAngle.y * ballSpeed), (worldAngle.z * ballSpeed)));
    100.                                         //PlayWhoosh();
    101.                                         audio.PlayOneShot(ballAudio);   //yes play an audio clip once pre instantiation
    102.                                        
    103.                                     }
    104.                                 break;
    105.                 default :
    106.                                     break;
    107.                                         break;
    108.  
    109.                 }//end switch case
    110.                 if (GetVelocity)
    111.                 {
    112.                     flickTime++;
    113.                 }
    114.             }
    115.         }
    116.         if (!shootEnable)
    117.         {
    118.             Debug.Log("shot disabled!");
    119.         }
    120.     }
    121.    
    122.     void timeIncrease()
    123.     {
    124.         if (GetVelocity)
    125.         {
    126.             flickTime++;
    127.         }
    128.     }
    129.    
    130.     void GetSpeed()
    131.     {
    132.         flickLength = 90;
    133.         if (flickTime > 0)
    134.         {
    135.             ballVelocity = flickLength / (flickLength - flickTime);
    136.         }
    137.         ballSpeed = ballVelocity * 30;
    138.         ballSpeed = ballSpeed - (ballSpeed * 1.65f);
    139.         if (ballSpeed <= -33)
    140.         {
    141.             ballSpeed = -33;
    142.         }
    143.         Debug.Log("flick was" + flickTime);
    144.         flickTime = 5;
    145.     }
    146.    
    147.     void GetAngle ()
    148.     {
    149.         worldAngle = camera.ScreenToWorldPoint(new Vector3 (touchEnd.x, touchEnd.y + 800.0f, ((camera.nearClipPlane - 100.0f)*1.8f)));
    150.     }
    151.     //no
    152. //  void PlayWhoosh()
    153. //  {
    154. //      GameObject sound = Instantiate(whoosh[Random.Range(0,whoosh.length)],transform.position,transform.rotation) as GameObject;
    155. //      Debug.Log("Whoosh!");
    156. //  }
    157. }
    158.  
    159.  
    160. Take care all
    161. Gruffy
    162.  
     
  19. JParish2590

    JParish2590

    Joined:
    Jan 8, 2014
    Posts:
    32
    hi i have looked through your code and was just wondering if there was anyway you help me narrow this down... i just want to have a simple swipe up function and make it do something AND a swipe down function and make that do something... any chance you could post it?
     
  20. hgaur725

    hgaur725

    Joined:
    Feb 20, 2014
    Posts:
    17
    dude its not working i used this script
     
  21. hgaur725

    hgaur725

    Joined:
    Feb 20, 2014
    Posts:
    17
    applied this script to the camera but when i test it on my kindle nothng works
     
  22. hgaur725

    hgaur725

    Joined:
    Feb 20, 2014
    Posts:
    17
    Soorry Folks!! it perfectly working.. emm prob was with me ball speed was too much and i was unable to see my ball.. its Perfect
     
  23. hgaur725

    hgaur725

    Joined:
    Feb 20, 2014
    Posts:
    17
    hey folks!! as i said earlier this script is working perfect but when i tested this on my device i found it working on whr evr u touch on whole screen... i want it to flick when i touch the ball.. i want it to flick when user touch the ball .. like paper toss game...
    thanx in advance :):):)
     
  24. hgaur725

    hgaur725

    Joined:
    Feb 20, 2014
    Posts:
    17
    can u tell how to use it on gameobject.. as u r using it on camera.. so whr evr touch on screen ball gets flicked.. but i want ball to got flicked when i touch it.. i hope u ll rply>> thnxx
     
  25. Vinamra_Dev

    Vinamra_Dev

    Joined:
    Apr 1, 2013
    Posts:
    1
    can plz explain how to make gesture of curve (ball is flicked on touch) it goes in curve..I am in big trouble.. Please explain...
     
  26. nik nik

    nik nik

    Joined:
    Jun 17, 2013
    Posts:
    1
    Hello,

    In line 66 there seems to be an error,probably something's missing?Could anyone help how to fix it?

    66. if (couldbeswipe swipeDist > comfortZone) {

    Is there something missing between couldbeswipe and swipeDist?

    Thanks in advance.
     
  27. Dvad

    Dvad

    Joined:
    Jun 24, 2014
    Posts:
    1
    =
     
  28. saddam751

    saddam751

    Joined:
    Nov 6, 2013
    Posts:
    41
    how to make parabolic path using same script
     
  29. Udit-Makwana

    Udit-Makwana

    Joined:
    Jun 1, 2013
    Posts:
    4
    I was doing the same thing and the script works fine but whereever I touch on screen the ball gets flicked
     
  30. Duderinho

    Duderinho

    Joined:
    Feb 2, 2014
    Posts:
    1
    Is there still anyone out there? Either script doesn't work for me and I don't know why. I set the script to my main camera and I assigned the gameobject and audioclip. The console does say "enabled!". Am I missing something really obvious? I'm sort of new to Unity, if anyone can help me out that would be awesome.
     
  31. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,041
    This was written on Jun 2, 2011 one might expect that Unity has changed a bit since then.
     
  32. SAOTA

    SAOTA

    Joined:
    Feb 9, 2015
    Posts:
    220
    Here...
    Working 5.2.3f1...

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. //demand an adio source be placed on this component for use with the audio clip
    5. //[RequireComponent(typeof(AudioSource))]
    6. public class FlickThrowTouch : MonoBehaviour
    7. {
    8.  
    9.     public Vector2 touchStart;
    10.     public Vector2 touchEnd;
    11.     public int flickTime = 5;
    12.     public int flickLength = 0;
    13.     public float ballVelocity = 0.0f;
    14.     public float ballSpeed = 0;
    15.     public Vector3 worldAngle;
    16.     public GameObject ballPrefab;
    17.     float swipeDist;
    18.  
    19.     private bool GetVelocity = false;
    20.     //public GameObject[] woosh; //no
    21. //    public AudioClip ballAudio;  //yes
    22.     public float comfortZone = 0.0f;
    23.     public bool couldBeSwipe;
    24.     public float startCountdownLength = 0.0f;
    25.     public bool startTheTimer = false;
    26.     static bool globalGameStart = false;
    27.     static bool shootEnable = false;
    28.     private float startGameTimer = 0.0f;
    29.  
    30.     private AudioSource asParamsControl;
    31.  
    32.     void  Start ()
    33.     {
    34.         //asParamsControl = this.gameObject.GetComponentInChildren<AudioSource>();
    35.     //    this.asParamsControl.playOnAwake = false;
    36.     //    this.asParamsControl.loop = false;
    37.         startTheTimer = true;
    38.         Time.timeScale = 1;
    39.         if ( Application.isEditor )
    40.         {
    41.             Time.fixedDeltaTime = 0.01f;
    42.         }
    43.     }
    44.  
    45.     void Update ()
    46.     {
    47.         if (startTheTimer)
    48.         {
    49.             startGameTimer += Time.deltaTime;
    50.         }
    51.         if (startGameTimer > startCountdownLength)
    52.         {
    53.             globalGameStart = true;
    54.             shootEnable = true;
    55.             startTheTimer = false;
    56.             startGameTimer = 0;
    57.         }
    58.  
    59.         if (shootEnable)
    60.         {
    61.             Debug.Log ("enabled!");
    62.             if (Input.touchCount > 0)
    63.             {
    64.                 var touch = Input.touches[0];
    65.                 switch (touch.phase)
    66.                 {
    67.                 case TouchPhase.Began:
    68.                     flickTime = 5;
    69.                     timeIncrease();
    70.                     couldBeSwipe = true;
    71.                     GetVelocity = true;
    72.                     touchStart= touch.position;
    73.                     break;
    74.                 case TouchPhase.Moved:
    75.                     if (Mathf.Abs(touch.position.y - touchStart.y) < comfortZone)
    76.                     {
    77.                         couldBeSwipe = false;
    78.                     }
    79.                     else
    80.                     {
    81.                         couldBeSwipe = true;
    82.                     }
    83.                     break;
    84.                 case TouchPhase.Stationary:
    85.                     if (Mathf.Abs(touch.position.y - touchStart.y) < comfortZone)
    86.                     {
    87.                         couldBeSwipe = false;
    88.                     }
    89.                     break;
    90.                 case TouchPhase.Ended:
    91.                     float swipeDist =(touch.position - touchStart).magnitude;
    92.                     //couldBeSwipe
    93.                     if (couldBeSwipe ||  swipeDist > comfortZone)
    94.                     {
    95.                         GetVelocity = false;
    96.                         touchEnd = touch.position;
    97.                         GameObject ball = Instantiate(ballPrefab, new Vector3(0.0f,0,-3.0f), Quaternion.identity) as GameObject;
    98.                         GetSpeed();
    99.                         GetAngle();
    100.                         ball.GetComponent<Rigidbody>().AddForce(new Vector3((worldAngle.x * ballSpeed), (worldAngle.y * ballSpeed), (worldAngle.z * ballSpeed)));
    101.                         //PlayWhoosh();
    102.                         //audio.PlayOneShot(ballAudio);   //yes play an audio clip once pre instantiation
    103.  
    104.                     }
    105.                     break;
    106.                 default :
    107.                     break;
    108.                     break;
    109.  
    110.                 }//end switch case
    111.                 if (GetVelocity)
    112.                 {
    113.                     flickTime++;
    114.                 }
    115.             }
    116.         }
    117.         if (!shootEnable)
    118.         {
    119.             Debug.Log("shot disabled!");
    120.         }
    121.     }
    122.  
    123.     void timeIncrease()
    124.     {
    125.         if (GetVelocity)
    126.         {
    127.             flickTime++;
    128.         }
    129.     }
    130.  
    131.     void GetSpeed()
    132.     {
    133.         flickLength = 90;
    134.         if (flickTime > 0)
    135.         {
    136.             ballVelocity = flickLength / (flickLength - flickTime);
    137.         }
    138.         ballSpeed = ballVelocity * 30;
    139.         ballSpeed = ballSpeed - (ballSpeed * 1.65f);
    140.         if (ballSpeed <= -33)
    141.         {
    142.             ballSpeed = -33;
    143.         }
    144.         Debug.Log("flick was" + flickTime);
    145.         flickTime = 5;
    146.     }
    147.  
    148.     void GetAngle ()
    149.     {
    150.         worldAngle = this.GetComponent<Camera>().ScreenToWorldPoint(new Vector3 (touchEnd.x, touchEnd.y + 50f, ((this.GetComponent<Camera>().nearClipPlane - 50.0f))));
    151.     }
    152.     //no
    153.     //  void PlayWhoosh()
    154.     //  {
    155.     //      GameObject sound = Instantiate(whoosh[Random.Range(0,whoosh.length)],transform.position,transform.rotation) as GameObject;
    156.     //      Debug.Log("Whoosh!");
    157.     //  }
    158. }
     
    W4rf4c3 likes this.
  33. RingK

    RingK

    Joined:
    May 2, 2016
    Posts:
    1
    Any hint on how to apply this to a 2D game? I've been trying 3 days with no results :(
     
  34. FoneFreak

    FoneFreak

    Joined:
    May 17, 2016
    Posts:
    16
    Is there a DUMMIES guide for setting this up in inspector?, I am trying it but (sphere) ball does not move?

    Also am I correct in thinking this will not work in Inspector and will only work on a device? (or will it work in unity inspector?

    thanks to all!
     
  35. patcosmos310

    patcosmos310

    Joined:
    Jan 30, 2015
    Posts:
    5
    It will work only on the device.To make it work in the inspector ,will have to change the code by replacing the TouchPhase and finding the swipe based on GetMouseButtonDown and GetMouseButtonUp
     
  36. vanshika1012

    vanshika1012

    Joined:
    Sep 18, 2014
    Posts:
    48
    I tried implement the code, with minor changes. I feel a offset distance between the actual touch and position of ball. I have attached the video link for reference.
     
  37. kelvin-w

    kelvin-w

    Joined:
    Nov 25, 2016
    Posts:
    74
    thanks alot for this! it is helping me alot. i only have 1 question. how can i make this for 2d sideview games (like tigerball)?
     
  38. kelvin-w

    kelvin-w

    Joined:
    Nov 25, 2016
    Posts:
    74
  39. nadhimali

    nadhimali

    Joined:
    Apr 4, 2015
    Posts:
    17
    my code is different but works the same

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. //attach this script to camera
    6. public class Flicking : MonoBehaviour {
    7.  
    8.     //Ball prefab
    9.     public GameObject Ball;
    10.     //where to spawn (a transform infront of camara or you can assign the camera
    11.     public Transform SpwanPoint;
    12.     private Vector2 StartTouch;
    13.     private Vector2 EndTouch;
    14.     //the min distance to count it as a flick
    15.     public float MinSwipDist = 0;
    16.     private float FlickerLength;
    17.     private float BallVelocity = 0;
    18.     private float BallSpeed = 0;
    19.     public float MaxBallSpeed = 40;
    20.     private float FlickTimer = 1.0f;
    21.     private bool GainSpeed = false;
    22.     private Vector3 angle;
    23.  
    24. //if you want to use audio.
    25. //public AudioClip Cick;
    26. //if you want to use a UI slider to show the kick force
    27. //public Slider sldr;
    28.  
    29.  
    30.     // Update is called once per frame
    31.     void Update () {
    32.        
    33.         //if you want to use a UI slider to show the kick force
    34.        // sldr.value = FlickTimer / 50;
    35.  
    36.         if(Input.touchCount > 0){
    37.             Touch touch = Input.touches [0];
    38.  
    39.             if (touch.phase == TouchPhase.Began) {
    40.                     StartTouch = touch.position;
    41.                     GainSpeed = true;
    42.             } else if (touch.phase == TouchPhase.Ended) {
    43.  
    44.                 //swap distance
    45.                 float swipdistance = (touch.position - StartTouch).magnitude;
    46.  
    47.                     if(swipdistance >  MinSwipDist){
    48.                         GameObject Ballx = Instantiate (Ball, SpwanPoint.position, Quaternion.identity);
    49.                         GainSpeed = false;
    50.                         EndTouch = touch.position;
    51.                         Speeds ();
    52.                         MoveAngle ();
    53.                         Ballx.GetComponent<Rigidbody> ().AddForce (new Vector3 ((angle.x * BallSpeed), (angle.y * BallSpeed),(angle.z * BallSpeed)));
    54.                          //play audio
    55.                         //GetComponent<AudioSource> ().PlayOneShot (Cick);
    56.                     }
    57.             }
    58.  
    59.             if(GainSpeed){
    60.                 //as soon as you are pressing the screen ball will gain speed
    61.                 FlickTimer += Time.deltaTime * 20;
    62.             }
    63.  
    64.         }
    65.     }
    66.  
    67.     void Speeds(){
    68.         FlickerLength = 90;
    69.         if(FlickTimer > 0){
    70.             BallVelocity = FlickerLength / (FlickerLength - FlickTimer);
    71.         }
    72.         BallSpeed = BallVelocity * 25;
    73.         BallSpeed = BallSpeed - (BallSpeed * 1.7f);
    74.         if (BallSpeed <= -MaxBallSpeed) {
    75.  
    76.             BallSpeed = -MaxBallSpeed;
    77.         }
    78.         FlickTimer = 1;
    79.     }
    80.  
    81.     void MoveAngle(){
    82.  
    83.         angle = this.GetComponent<Camera> ().ScreenToWorldPoint (new Vector3 (EndTouch.x, EndTouch.y + 50f, (this.GetComponent<Camera> ().nearClipPlane - 50.0f)));
    84.     }
    85. }
    86.  
     
    augivision likes this.
  40. JoMaHo

    JoMaHo

    Joined:
    Apr 2, 2017
    Posts:
    94
    Nice one!
    Did not get the sound to play; added the AudioSoure component, attached a swish.wav file to the script, but it does not play at swipe. Any suggestions?
     
  41. ghufronhasan23

    ghufronhasan23

    Joined:
    Aug 17, 2016
    Posts:
    7
    how i use script for parabolic throw ball used kinect control ? if i have path, how to ball throwing not always into ring. is that velocity or what ?
     
  42. zero_null

    zero_null

    Joined:
    Mar 11, 2014
    Posts:
    159
    Hello, Can anyone help me integrate this for a 2d game ? I am banging my head in from so many days. Also I need it implemented with mouse clicks as well. Please please help me.
     
  43. wacasce

    wacasce

    Joined:
    Sep 14, 2017
    Posts:
    4
    did you manage to find out how to flick i a 2d game
     
  44. kelvin-w

    kelvin-w

    Joined:
    Nov 25, 2016
    Posts:
    74
    zero_null likes this.
  45. javilumb

    javilumb

    Joined:
    May 29, 2017
    Posts:
    1
    Hi guys,

    Just thought of sharing my experience with this in case anyone stumbles upon across with the same issue:

    First of all, thank you very much for sharing those scripts, tried both and worked really well for my purposes. However, be aware of this particular bit of code:
    worldAngle = this.GetComponent<Camera>().ScreenToWorldPoint(new Vector3 (touchEnd.x, touchEnd.y + OFFSET, ((this.GetComponent<Camera>().nearClipPlane - 50.0f))));​

    That offset, applied BEFORE converting the screen point into a world point, may lead to completely different results on devices with different screen resolutions.

    For instance, the script was working fine on my Nexus 5 or my Xiaomi Redmi 4x, but on my old HTC 500 with 4,5' inches screen the balls were thrown to a completely different direction, making the game unplayable. My solution was applying the offset (obviously you'll need to adjust this value again) after the point has been converted:

    worldAngle = this.GetComponent<Camera>().ScreenToWorldPoint(new Vector3 (touchEnd.x, touchEnd.y, ((this.GetComponent<Camera>().nearClipPlane - 50.0f))));
    worldAngle.y += OFFSET;
    Not sure if this is the best solution but so far looks like it works well across all devices and resolutions :)
    Hope it helps!

    Cheers,
    J
     
  46. augivision

    augivision

    Joined:
    Mar 27, 2018
    Posts:
    14

    I made sure my prefab had a rigidbody and use gravity. All I had to do was create an empty game object in front of my camera for the ball spawn, drag it onto this script in the inspector, then drag my ball prefab and set the Max Ball Speed to 5 for now AN IT WORKS GREAT! THANK YOU!
     
  47. augivision

    augivision

    Joined:
    Mar 27, 2018
    Posts:
    14

    How can I get this to work on an object that I touch?
    If I have my ball visible on-screen and want to grab it and throw it, instead of having it instantiate?

    Code (CSharp):
    1. if(hit.collider.tag = "Ball")
    2. {
    3.     //what lines of code would I place inside this bracket?
    4. }
    Also, I am pretty sure I would delete line 48 and add it in my BallMissedTarget() instead.
     
  48. Adishah11

    Adishah11

    Joined:
    Aug 10, 2015
    Posts:
    9
  49. CoreApp2

    CoreApp2

    Joined:
    Sep 8, 2015
    Posts:
    3
    Hello dear people, i do realy need your help

    I have a circle on the ground, a 3D sphere or ball that always looks in the direction of the circle, and the camera that always follows the ball from behind. I throw the ball by swiping it from position 1, it falls on the ground, rolls to position 2. Then when I try again to throw the ball from position 2, it always tries to roll forward (in the false direction/false thrown), and not in the correct direction (correct thrown.) You can have a look at the data Description. How can I throw the ball by swiping in the direction the camera is facing?

    This is how the code looks like

    Code (CSharp):
    1. bool thrown, holding;
    2. Vector3 offsetValue;
    3. Rigidbody ball_RigiB;
    4. GameObject gObj = null;
    5. float startTime, endTime, tempTime, swipeDistance, swipeTime,speed;
    6.  
    7. private void Update()
    8. {  
    9.     if (Input.GetMouseButtonDown(0))
    10.     {
    11.         // hold the ball
    12.         RaycastHit hit;
    13.         gObj = ReturnClickedObject(out hit);
    14.  
    15.         if (gObj != null && gObj.transform.gameObject.tag == "3dCircle" )
    16.         {
    17.             holding = true;
    18.             //calc mouse offset
    19.             //Converting world position to screen position.
    20.             positionOfScreen = Camera.main.WorldToScreenPoint(gObj.transform.position);
    21.             offsetValue = gObj.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, positionOfScreen.z));
    22.         }
    23.        
    24.         Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    25.         if (Physics.Raycast(mouseRay, out hit, 1000f) && gObj.transform.gameObject.tag == "3dCircle" )
    26.         {
    27.             //Prepare the ball for the swipe motion
    28.             startTime = Time.time;
    29.             startPos = Input.mousePosition;
    30.            
    31.             //Alternativ, but dont work
    32.             //startPos.z = gObj.transform.position.z - Camera.main.transform.position.z;
    33.             //startPos = Camera.main.ScreenToWorldPoint(startPos);
    34.            
    35.             holding = true;
    36.         }
    37.     }
    38.     else if (Input.GetMouseButtonUp(0) && gObj)
    39.     {
    40.         //Prepare the ball for the swipe motion (end phase)
    41.         endTime = Time.time;
    42.         endPos = Input.mousePosition;
    43.        
    44.         // Alternativ, for z direction, :((
    45.         //endPos.z = gObj.transform.position.z - Camera.main.transform.position.z;
    46.         //endPos = Camera.main.ScreenToWorldPoint(endPos);
    47.            
    48.         swipeDistance = (endPos - startPos).magnitude;
    49.         swipeTime = endTime - startTime;
    50.  
    51.         if (swipeTime < FlickSpeed && swipeDistance > swipeDistanceLimit)
    52.         {
    53.             direction = endPos - startPos;
    54.             direction.z = direction.magnitude;
    55.             direction.Normalize();
    56.            
    57.             //throw the ball
    58.             speed_ = swipeDistance / swipeTime;
    59.             ball_RigiB.AddForce(direction * speed_, ForceMode.Force);
    60.            
    61.             holding = false; isSwiped = true;
    62.             Invoke("setBallOnCircle", 6f);
    63.         }
    64.         else
    65.         {
    66.             _Reset();
    67.         }
    68.         gObj = null;
    69.     }
    70. }
    71.    
    72. private void _Reset()
    73. {
    74.     ball_RigiB.velocity = Vector3.zero;
    75.     ball_RigiB.angularVelocity = Vector3.zero;
    76.     ball_RigiB.useGravity = false;
    77.     thrown = false; holding = false;
    78. }
    79.  
    I hope you could help me
    Thanks
     

    Attached Files:

  50. makaka-org

    makaka-org

    Joined:
    Dec 1, 2013
    Posts:
    1,004