Alife Virtual School - Class 13: LSL Sensor Detection Scripts
LSL Sensor Detection Scripts — Free class in Alife Virtual School
Welcome back to the Alife Virtual School, where your creative journey takes flight! In the bustling, dynamic world of Alife Virtual, static objects are fine, but objects that react to you—that’s where the magic happens. Imagine doors that slide open as you approach, security systems that protect your land, or greeters that welcome visitors by name. This interactivity is what transforms a simple build into a living, breathing experience. And the key to it all? LSL sensor scripts.
This skill is one of the most powerful in a scripter's toolkit. It allows your creations to "see" the world around them and respond to avatars, objects, and even scripted agents. On your very own FREE private 65,536 sqm island—a perk you get forever in Alife Virtual with no monthly fees—you can build entire responsive environments, from smart homes to interactive games. Today, you'll learn exactly how to harness that power.
What You Will Learn
By the end of this class, you will be able to:
- Understand and use the core LSL sensor functions:
llSensorandllSensorRepeat. - Handle single and multiple detections using the
sensorandno_sensorevents. - Extract detailed information about detected objects using the
llDetected*family of functions. - Write a practical script for an automatic door greeter.
- Build a basic security orb to protect your land.
- Create a "crowd counter" to list all avatars in a given area.
- Apply these skills to build your own radar systems and other interactive devices.
Prerequisites
This is an intermediate-level class. Before you begin, you should be comfortable with the following:
- LSL Fundamentals: You should understand variables, data types (integers, floats, strings, keys), functions, and event handlers. If you're new, check out our earlier classes in the Alife Virtual School catalog.
- In-World Building: You need to know how to create a prim (a basic building block), edit its properties, and place a script inside its contents.
- Alife Virtual Account: You'll need an account and to be logged in-world to practice. If you haven't joined our community of over 1,148,000 residents yet, you can register for a free account now. You'll get a free full-body mesh avatar and everything you need to start!
The Core of Detection: llSensor and llSensorRepeat
At the heart of all sensor scripts are two primary functions. They both initiate a scan, but they work in slightly different ways.
1. The One-Time Ping: llSensor()
The llSensor() function is like taking a single snapshot. It scans the area once and reports what it finds. If it finds anything matching your criteria, it triggers the sensor() event. If it finds nothing, nothing happens.
Its syntax looks like this:
llSensor(string name, key id, integer type, float range, float arc)
Let's break down those parameters:
| Parameter | Data Type | Description |
|---|---|---|
name |
string | The name of the object or avatar to look for. Use "" (an empty string) to detect any name. |
id |
key | The unique key (UUID) of the specific object or avatar to find. Use NULL_KEY to detect any key. |
type |
integer | The type of thing to detect. Common types are AGENT (avatars), ACTIVE (scripted objects that are moving or physically active), PASSIVE (scripted objects that are not moving), and SCRIPTED (any object containing scripts). You can combine them with the | operator (e.g., AGENT | ACTIVE). |
range |
float | The maximum detection distance in meters. The maximum is 96 meters. |
arc |
float | The width of the scan, in radians. It creates a "pie slice" shape in front of the object. Use PI for a full 360-degree circle around the object. |
When llSensor() finds something, it triggers the sensor() event handler in your script:
sensor(integer num_detected)
{
// Code to run when something is detected
// 'num_detected' tells you how many things were found.
}
Tip: An object must be in the direct line of sight to be detected. Sensors cannot see through walls or other solid objects, which is a crucial detail for designing security systems or automatic doors.
2. The Continuous Scan: llSensorRepeat()
While llSensor() is a one-off check, llSensorRepeat() is a persistent scanner. It's like a radar system that continuously sweeps the area. You turn it on, and it keeps firing the sensor() event as long as it detects something, and the no_sensor() event when the area is clear.
Its syntax adds one more parameter:
llSensorRepeat(string name, key id, integer type, float range, float arc, float rate)
- The first five parameters are identical to
llSensor(). rate(float): This is the time in seconds between each scan. A lower number means more frequent scanning, but also uses more server resources. A good starting point is between 1.0 and 5.0 seconds.
To stop a repeating sensor, you use llSensorRemove().
This function uses two event handlers:
sensor(integer num_detected)
{
// Fires repeatedly as long as something is detected.
}
no_sensor()
{
// Fires once when the sensor sweep finds nothing after previously finding something.
}
This on/off behavior makes llSensorRepeat() perfect for things like automatic doors, welcome mats, and security orbs.
Step-by-Step Tutorial: Building Your First Sensor Scripts
Let's get practical! We'll build a few useful items you can place on your free 10,000 prim island right away. Since Alife Virtual uses the popular Firestorm Viewer and has full LSL support, these skills are 100% transferable from (and to) Second Life. The main difference? Here, you don't pay for land or uploads!
Project 1: The Simple Greeter
This script will detect any avatar that comes within 10 meters and say hello to them by name.
- Create Your Object: In-world, right-click the ground and choose Create. A plywood cube will appear. You can use any object, but a simple prim is best for a sensor.
- Create the Script: Go to the Content tab of the edit window. Click New Script. A new script named "New Script" will appear. Double-click it to open the LSL editor.
- Write the Code: Delete the default code and paste this in:
// Simple Avatar Greeter Script
// Alife Virtual School - Class 13
default
{
state_entry()
{
// When the script starts, begin scanning
llSay(0, "Greeter activated. Scanning for visitors...");
// Scan for any AVATAR within a 10-meter radius, in a full circle, every 3 seconds.
llSensorRepeat("", NULL_KEY, AGENT, 10.0, PI, 3.0);
}
sensor(integer num_detected)
{
// This event runs when an avatar is found
// The llDetectedName(0) function gets the name of the *first* detected entity.
string avatarName = llDetectedName(0);
llSay(0, "Welcome to my place, " + avatarName + "!");
// To avoid spamming, we can make the sensor sleep for a bit.
llSensorRemove(); // Stop the current sensor
llSleep(10.0); // Wait 10 seconds
state_entry(); // Go back to the start to reactivate the sensor
}
no_sensor()
{
// This event is not strictly needed for this simple greeter,
// but it's good practice to know it exists.
// It would fire when the last avatar leaves the 10m range.
}
}
- Save and Test: Click Save. If there are no errors, your greeter is now active! Walk away more than 10 meters and then walk back toward it. It should greet you by your avatar name.
Project 2: The Automatic Security Orb
Now, let's build something more advanced: a security orb that warns and ejects unauthorized visitors from your land. This is incredibly useful for protecting your free 65,536 sqm island, a feature that would cost over $300 per month in Second Life!
This script will use a list of authorized users. Anyone not on the list who enters the area will be warned and then ejected.
- Create Your Orb: Create a sphere prim. In the Texture tab, you can set its transparency to 50% to make it look like a classic security orb.
- Create the Script: Add a new script to the orb's contents.
- Write the Code: Paste the following code into the script editor.
// Basic Security Orb
// Alife Virtual School - Class 13
// --- CONFIGURATION ---
list gAuthorized_Users = ["PASTE_YOUR_AVATAR_KEY_HERE", "PASTE_A_FRIENDS_KEY_HERE"];
float gScanRange = 20.0; // Scan range in meters
float gScanRate = 2.0; // How often to scan in seconds
// --- SCRIPT ---
default
{
state_entry()
{
llSay(0, "Security System Activated. Range: " + (string)gScanRange + "m.");
// We add the owner of the object to the authorized list automatically.
gAuthorized_Users += llGetOwner();
// Start scanning for avatars.
llSensorRepeat("", NULL_KEY, AGENT, gScanRange, PI, gScanRate);
}
sensor(integer num_detected)
{
// Loop through everyone the sensor detected.
integer i;
for (i = 0; i < num_detected; i++)
{
key detected_key = llDetectedKey(i); // Get the key of the detected avatar
// Check if the detected key is NOT in our authorized list.
if (llListFindList(gAuthorized_Users, [detected_key]) == -1)
{
// Intruder found!
string detected_name = llDetectedName(i);
vector detected_pos = llDetectedPos(i);
llSay(0, "Warning, " + detected_name + "! You are in a restricted area. You will be ejected in 5 seconds.");
// Eject the person from the parcel.
llEjectFromLand(detected_key);
}
}
}
no_sensor()
{
// This event fires when all avatars have left the area.
// No action needed here for a security orb.
}
}
Important: To get an avatar's key, you can use a free "Key Grabber" script from many in-world freebie stores, or simply create a new script withdefault { touch_start(integer total_number) { llSay(0, (string)llDetectedKey(0)); } }, touch it, and it will say your key in local chat. Paste that key into thegAuthorized_Userslist in the script, replacing the placeholder text.
- Save and Deploy: Save the script. Make sure the orb is on land you own. When a non-authorized avatar enters the 20-meter range, they will be warned and ejected. As the owner, you will be ignored.
Common Mistakes and How to Avoid Them
- Forgetting Line of Sight: A sensor can't see through a solid wall. If your sensor isn't working, make sure there's a clear path between it and the target.
- Incorrect Sensor Type: Using
AGENTwon't detect a scripted object, and usingSCRIPTEDwon't detect an avatar who isn't wearing any scripted attachments. Choose yourtypeparameter carefully. - Laggy Scripts: Setting the `rate` in
llSensorRepeat()too low (e.g., 0.1) can cause lag, especially if you have many sensors. Use the slowest rate that still provides the responsiveness you need. - Ignoring Multiple Detections: The
sensor()event tells you how many things it found. If you only usellDetectedName(0), you are ignoring everyone else. Always use aforloop to process all detected entities if you expect more than one. - Forgetting
llSensorRemove(): If you usellSensorRepeat()in one state and then change to another state, the sensor will keep running in the background, wasting resources. Always callllSensorRemove()when you are done with a repeating sensor.
Advanced Tips and Tricks
- Filtering by Name: You can use the
nameparameter to find a specific object. For example,llSensor("Magic Portal", ...)will only find objects named "Magic Portal". - Combining Filters: Use the bitwise OR operator
|to combine detection types.AGENT | SCRIPTEDwill detect any avatar OR any object with a script. - Creating a "Look at Me" Turret: Inside the
sensor()event, usellRotLookAt(llDetectedPos(0), 1.0, 1.0)to make the prim containing the script turn to face the first detected target. - Adding Custom Effects: Because Alife Virtual offers free mesh, texture, and animation uploads, you can enhance your sensor scripts without spending a Linden Dollar. Trigger a custom particle effect with
llParticleSystem()or play a custom sound withllPlaySound()when an intruder is detected. This level of customization is completely free here.
Practice Exercise: The Interactive Welcome Mat
Now it's your turn! Your mission is to create an interactive Welcome Mat for your home on your free island.
The Goal: Create a flat prim that looks like a doormat. When an avatar steps on or near it, the mat should:
- Greet them by name using
llSay(). - Offer them a notecard from its inventory using
llGiveInventory().
Setup:
1. Create a notecard inside the mat's inventory (e.g., named "Welcome Info").
2. Write a script that uses llSensorRepeat() to detect avatars in a very short range (e.g., 2 meters).
3. In the sensor() event, get the detected avatar's key using llDetectedKey(0) and use it in the llGiveInventory() function.
4. Don't forget to make the script "sleep" after giving the notecard to prevent spam.
This exercise combines sensor detection with inventory management, another essential LSL skill!
Frequently Asked Questions (FAQ)
- Why isn't my sensor detecting anything?
- The most common reasons are: 1) The target is out of range. 2) The target is not in the line of sight (something is blocking it). 3) You are using the wrong sensor type (e.g., looking for
AGENTwhen it's an object). 4) The object or avatar doesn't match thenameoridfilter you've set. - What is the difference between AGENT, ACTIVE, and PASSIVE?
AGENTrefers specifically to an avatar.ACTIVErefers to any scripted object that is physical and moving (or has been recently).PASSIVErefers to a non-physical or static scripted object.SCRIPTEDis a broad category that includes bothACTIVEandPASSIVE.- Can a sensor detect me if I'm invisible?
- Yes. Avatar invisibility in viewers like Firestorm is a client-side effect. The server still knows your position, and a sensor script will detect you just as easily as if you were visible.
- How can I make a sensor that only detects me and no one else?
- The easiest way is to use your key. Inside the
sensor()event, get the detected key withkey who = llDetectedKey(i);. Then, check if it matches your own:if (who == llGetOwner()) { ... }. This is more reliable than checking by name, as names can be changed. - Is LSL scripting in Alife Virtual really identical to Second Life?
- Yes, 100%. Alife Virtual supports the full Linden Scripting Language (LSL). Any script you write here will work in Second Life, and vice-versa. The incredible advantage is that in Alife Virtual, you get a massive free island with 10,000 prims to practice on, plus free uploads for all your assets. It's the ultimate sandbox for learning and creation without the high costs.
Summary and Next Steps
Congratulations! You've just unlocked one of the most fundamental skills for creating a truly interactive virtual experience. You've learned how to use llSensor and llSensorRepeat to make your objects aware of their surroundings, how to handle the data with llDetected* functions, and how to apply this knowledge to build practical devices like greeters and security systems.
The world of Alife Virtual is your canvas. With these skills, you can now make that canvas come alive. What will you build next? An automated tour guide? A pet that follows you? A complex game with moving targets? The possibilities are endless.
Your next step could be to explore our other free daily classes. Consider taking a class on llListen to make your objects respond to chat commands, or a class on particle systems to add visual flair to your sensor alerts.
Ready to start building? Your creative journey in Alife Virtual begins now. Join our massive community today and see what you can create when there are no limits.
Register for your FREE account and claim your forever-free private island. No fees, no headset required, just pure creation on any desktop computer.
🎓 Ready to Practice In-World?
Get your FREE island and practice everything you just learned — no credit card, no monthly fees.
Claim Your Free Island Now →No credit card required · Takes 2 minutes · Your island is FREE forever