11

i'm currently making a soccer game.

In this mini-game, when the player touch the ball, it adds force, and the goal is to make the higher score.

So i wrote:

 void Update()
{
    if(Input.touchCount == 1 && Input.GetTouch(0).phase== TouchPhase.Began)
      {
       AddForce, and playsound ect...
      }

}

With this, when i touch anywhere on the screen, it adds force, but i just want to add force when i touch my gameobject (the ball).

How can i do that?

Thanks! :)

Programmer
  • 121,791
  • 22
  • 236
  • 328
Ophélia
  • 241
  • 2
  • 6
  • 16
  • is the soccer ball 2D Sprite/Image or 3D mesh? – Programmer Jul 25 '16 at 10:52
  • it's a 3d mesh, and the game looks like the soccer mini game in facebook messenger. – Ophélia Jul 25 '16 at 11:03
  • *All answers including mine used raycast but this is the old way to do this. There is a new way to do this now which makes raycast not appropriate for detecting taps on objects due to clicks going through UI objects. See the duplicate for more information.* – Programmer May 17 '18 at 04:31
  • FULLY MODERN APPROACH https://stackoverflow.com/questions/40323677/using-unity3ds-ipointerdownhandler-approach-but-with-the-whole-screen – Fattie Jan 23 '19 at 16:39

4 Answers4

16

With this, when i touch anywhere on the screen, it adds force, but i just want to add force when i touch my gameobject (the ball).

To detect tap on a particular GameObject, you have to use Raycast to detect click on that soccer ball. Just make sure that a collider(eg Sphere Collider) is attached to it.

void Update()
{
    if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
    {
        Ray raycast = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
        RaycastHit raycastHit;
        if (Physics.Raycast(raycast, out raycastHit))
        {
            Debug.Log("Something Hit");
            if (raycastHit.collider.name == "Soccer")
            {
                Debug.Log("Soccer Ball clicked");
            }

            //OR with Tag

            if (raycastHit.collider.CompareTag("SoccerTag"))
            {
                Debug.Log("Soccer Ball clicked");
            }
        }
    }
}
Programmer
  • 121,791
  • 22
  • 236
  • 328
7

Use OnMouseDown() in your script. Here is an example:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void OnMouseDown() {
        Application.LoadLevel("SomeLevel");
    }
}

P.S : remove that previous code from Update() method.


EDIT : Alternative code for mobile devices

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class OnTouchDown : MonoBehaviour
{
    void Update () {
        // Code for OnMouseDown in the iPhone. Unquote to test.
        RaycastHit hit = new RaycastHit();
        for (int i = 0; i < Input.touchCount; ++i) {
            if (Input.GetTouch(i).phase.Equals(TouchPhase.Began)) {
            // Construct a ray from the current touch coordinates
            Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
            if (Physics.Raycast(ray, out hit)) {
                hit.transform.gameObject.SendMessage("OnMouseDown");
              }
           }
       }
    }
}

Attach the above script to any active gameObject in the scene and OnMouseDown() will work for mobile devices as well.

Umair M
  • 10,298
  • 6
  • 42
  • 74
  • i don't think the mouseDown will work because i work on touch device. – Ophélia Jul 25 '16 at 11:21
  • 1
    @Ophélia add this script to your scene and now you can work with `OnMouseDown()` as usual. make your `OnMouseDown()` method `public`. – Umair M Jul 25 '16 at 11:28
  • I use void OnMouseDown(), and it works on android devices. Thanks a lot guys :) (and specialy Umair M.) ;) – Ophélia Jul 25 '16 at 16:10
  • No problem. Please mark my answer as correct for later users :) – Umair M Jul 25 '16 at 16:13
  • How can I use this in a generic way? Like if it hits object x, do y, if it hits object z, do w. – savram Dec 09 '18 at 03:17
  • you can user CompareTag() to see if the ray is hitting an object with a certain tag. hit.transform.gameObject IS the object that is being hit. – Umair M Dec 10 '18 at 15:02
0

You need to do several items here

  1. you need to raycast the touch to determine if the ball is touched

  2. you need to increment the power on the duration of the touch

  3. you need to fire the ball and reset the power on release of the touch


The code example here shows how to handle the rayCast

the code example here should help you with part 2

3 is nice and simple you just need to trigger your launch code an reset on Ended

put them together and you will get something like this

public class ExampleClass : MonoBehaviour {

    void FixedUpdate() {
       for (int i = 0; i < Input.touchCount; ++i) {
           Ray camRay = Camera.main.ScreenPointToRay (Input.GetTouch(i).Position);
           RaycastHit ballHit;
           if(Physics.Raycast (camRay, out ballHit, camRayLength, ballMask))
           {
               if (Input.GetTouch(i).phase == TouchPhase.Stationary) {
                   power += speed + Time.deltaTime;             
               }

               else if (Input.GetTouch(i).phase == TouchPhase.Ended) {
                   LauchBall(power);
                   power = 0;        
               }
           }
        }
    }
}

NOTE:code is for example only it has not been tested and is not complete

this uses the physics update as the trigger you can instead link directly to an objects triggers as suggested by some of the other answers

MikeT
  • 5,398
  • 3
  • 27
  • 43
  • 3
    never use FixedUpdate – Fattie Jul 25 '16 at 13:36
  • i admit i'm fairly new to Unity, so i'm not at a high enough level to decide between what works and what's best, but the Unity teams own examples use fixed update as the principle process for managing user input eg https://unity3d.com/learn/tutorials/projects/survival-shooter/player-character?playlist=17144 – MikeT Jul 25 '16 at 13:41
  • Unfortunately (much of) Unity's documentation is total, complete, crap – Fattie Jul 25 '16 at 13:43
  • in that case i would be interested if you can suggest a better source of documentation, – MikeT Jul 25 '16 at 13:46
  • there is none really, Mike - just read the 10000s of QA about Unity on here and elsewhere. don't forget Update simply means "every frame". with **the problem at hand here** you would of course want to do it every frame. (it would be pointless/bizarre to wait for the physics frames, or any other issue.) regarding FixedUpdate. (no connection at all to the problem at hand here.) it's just kind of a way to avoid doing the math when adding forces, you know? if you're doing something that takes place over a period of time. it's a bad idea in any game engine, and a source of huge confusion in Unity – Fattie Jul 25 '16 at 13:52
  • I just use void OnMouseDown(), and it works on my android device. – Ophélia Jul 25 '16 at 16:11
0

Take Touch Event using Co-Rouitne will be good for you. If you will not use coroutine, then it constant check for touch event in OnUpdate. Its better to take touch event in co-routine. This is my link in which you can check how to use it.


http://unitycodestuff.blogspot.in/2017/11/how-to-use-co-routine-for-taking-touch.html