Mouse

Written by: Headmaster
vector last_vel;
vector last_pos;
integer STAYING = 1;
integer FOLLOWING = 2;
integer mouse_state = FOLLOWING;
integer total = 0;

play_sound()
{
    integer num = llGetInventoryNumber(INVENTORY_SOUND);
    integer rand = (integer)(llFrand(num));
    llTriggerSound(llGetInventoryName(INVENTORY_SOUND, rand), 1.0);
}

default
{
    on_rez(integer p)
    {
        llSetStatus(STATUS_ROTATE_X | STATUS_ROTATE_Y, FALSE);
        llSetStatus(STATUS_DIE_AT_EDGE | STATUS_PHYSICS, TRUE);
        llSensorRepeat("", llGetOwner(), AGENT, 50.0, PI, 5.0);
        llListen(0, "", llGetOwner(), "");
        llSetTimerEvent(1.0);
    }
    
    listen(integer channel, string name, key id, string message)
    {
        if (message == "stay")
        {
            mouse_state = STAYING;
        }
        else if (message == "follow")
        {
            mouse_state = FOLLOWING;
        }
    }

    sensor(integer total_number)
    {
        llSetTimerEvent(1.0);
        last_vel = llDetectedVel(0);
        last_pos = llDetectedPos(0);
        vector direction = last_pos - llGetPos();
        float distance = llVecMag(direction);
        direction = llVecNorm(direction);
        float frot = llFrand(TWO_PI);
        rotation rot = llEuler2Rot(<0,0,frot>);
        llRotLookAt(rot, 0.1, 0.1);
        if (llVecMag(last_vel) < 0.25)
        {
            last_vel = direction;
        }
        else
        {
            last_vel = llVecNorm(last_vel);
            last_vel.z += 1.0;   
        }
        if (distance > 10.0)
        {
            direction += last_vel;
            direction.z += 3.0;
        }
        else if (distance > 2.0)
        {
            direction.z += 1.0;
            direction *= 0.75;
        }
        else
        {
            direction = <0,0,1>;
        }
        if (mouse_state == FOLLOWING)
            llApplyImpulse(direction*0.1, FALSE);
        else
            llApplyImpulse(<0,0,0.1>, FALSE);
    }
    
    timer()
    {
        if (total > 10)
        {
            while (llEdgeOfWorld(llGetPos(), last_vel))
            {
                last_vel = ;
            }
            float frot = llFrand(TWO_PI);
            rotation rot = llEuler2Rot(<0,0,frot>);
            llRotLookAt(rot, 0.1, 0.1);
            if (mouse_state == FOLLOWING)
                llApplyImpulse(last_vel*0.1, FALSE);
            else
                llApplyImpulse(<0,0,0.1>, FALSE);
            total = 0;
        }
        else
        {
            total += 1;
            if (llFrand(1.0) > 0.75)
            {
                play_sound();
            }
        }
    }
}