2D Onmousebutton function

Hi, I’m afraid I’m not as proficient with scripting as of yet and I wanted to just make a virtual pet type of simulation game using the new unity 2d features. I wanted it to be so that when you press + hold the left mouse button over the creature and move it around to simulate petting, it would change animation (using a sprite sheet by the way) from it’s default/idle animation to it becoming happier because you’re petting it. And when you release, it would go back to it’s default animation. I managed to do that, but it doesn’t seem to matter where I click. I was wondering how I could add to this script to get it to work so that it only changes animation when the mouse is over the creature.

 #pragma strict
var anim: Animator;

function Start () 
{
anim = GetComponent("Animator"); //Access character animations.
}

function Update ()
{ 
if (Input.GetMouseButton(0)) //Press and hold left mouse button to interact.
{ 
anim.SetTrigger("Rub");
} 

else if (Input.GetMouseButtonUp) //Release left mouse button to return to stop interacion.
{ 
 anim.SetTrigger("NoRub");
} 

}

You should check whether the mousePosition is currently on top of the pet. You could do that with a raycast from the screenPoint, something like:

var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit = Physics.Raycast (ray);

// If there's something at the mouse (hit by the ray)
if (hit) {

    // Check if the ray hit a gameObject tagged as pet.
    // I'm just quickly assuming you're using tags for now (as example.)
    if (hit.gameObject.tag == "Pet") { 
       anim.SetTrigger("Rub");
    }
}

Also see this question and answer.