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! :)
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");
}
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With