- Home /
Trying to detect mouse click or tap on a gameobject, why would not it work?
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class GameController : MonoBehaviour { int score = 0; int force = 1000;
// Move balloons
void Update()
{
//Calls bounce method each time button is clicked on a balloon
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Balloon"))
{
Debug.Log("Touched a balloon");
//hit.rigidbody.AddForce(ray.direction * hitForce);
}
}
/*if tapped on a balloon, bounces it
if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
{
Debug.Log("Touched screen");
Ray raycast = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit raycastHit;
if (Physics.Raycast(raycast, out raycastHit))
{
if(raycastHit.collider != null)
{
Debug.Log("Touched a balloon");
score = +1;
/*Rigidbody bl;
bl = raycastHit.rigidbody;
score++;
bl.AddForce(0, force, 0);
}
}
}*/
}
}
Does the gameobject have a collider? Raycasts are fired using the Physics class, so you would need some sort of physics in there for it to detect a hit.
They have polygon collider each.
Are you sure the polygon collider matches up with the mesh? (Also, is your game 2D?)
You can also use Debug.DrawRay to draw the ray in your scene view to make sure that it's actually hitting the object.
Answer by Connermarbut · Jan 05, 2021 at 11:37 PM
So testing it myself. It looked as if Unity wanted to know what the camera was. I made a private variable called cam, gave the camera the MainCamera tag. and then called it by tag.
private Camera cam;
void Start()
{
cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}
void Update()
{
//Calls bounce method each time button is clicked on a balloon
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Balloon"))
{
Debug.Log("Touched a balloon");
//hit.rigidbody.AddForce(ray.direction * hitForce);
}
}
Your answer
Follow this Question
Related Questions
Android Tap detection 2 Answers
Tapping iAd via AdMob is triggering RANDOM clicks on sprites in my scene. 1 Answer
Mobile Tap Issue 1 Answer
Tap to click on Mac touchpad 0 Answers
Player to look at 0 Answers