- Home /
Detect if mouse is inside an object (without OnMouseDown, etc)
I'm currently coding a gravity gun (like in half life) and it's suppose to be able drag objects base two condition: is the object inside the effective range? is the mouse clicked on the object?
To detect the range, I used a trigger BoxCollider2D on the gun. In the object script, I wrote the following:
using UnityEngine;
using System.Collections;
public class gunControle : MonoBehaviour
{
private GameObject player;
private Vector3 mousePos;
private bool hit;
void Start ()
{
player = transform.Find ("/player").gameObject;
}
// Update is called once per frame
void Update ()
{
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
hit = Physics2D.OverlapPoint (mousePos);
}
void OnTriggerStay2D (Collider2D other)
{
if (other.gameObject.tag == "gunRange") {
Debug .Log (hit);
if (Input.GetMouseButton (0) && hit) {
Debug.Log ("work");
transform.parent = player.transform;
} else {
transform.parent = null;
}
}
}
}
right now when the object is in the effective range, and mouse is in the effective range, it shows "hit" as true, and when mouse is outside the range it shows "false". However, I need it to be when object is inside effective range, and mouse is inside object, then "hit" is true. A lot of the solutions suggested OnMouseDown but I'm doing this inside OnTrigger, so is there another way?
Your answer
Follow this Question
Related Questions
Push object in direction of camera 0 Answers
HELP C# script mouse position doesn't work 1 Answer
onmousedown on object teleport 1 Answer
Mouse Click Teleportation with 2.5d game 0 Answers
Object rotation 2 Answers