Portal    Foro    Buscar    FAQ    Registrarse    Conectarse
Publicar Nuevo Tema  Responder al Tema  Mensaje de Gracias Página 1 de 1
 
Script De Animales Sociales En SL
Autor Mensaje
Responder Citando  
Mensaje Script De Animales Sociales En SL 
 
Hare 3 mensajes, primero la explicacion del autor, despues el codigo y luego explicare el codigo por partes


EXPLICACION DEL AUTOR
====================
The swarm algorithm in its purest sense creates any number of things that are attracted to each other. Any objects you tie this script to (after modifying the configurable parameters according to your object size, desired speed, etc) behave like social animals. That is, they swarm/flock/school... whatever you want to call it. None of generated movement is random, though it may appear to be.

Swarm rules for each swarm object to follow:
1. Accelerate toward the halfway point between your two nearest neighbors.
2. Upon collision, momentarily be repulsed by whatever object or ground was collided with.
3. If no neighbors are detected, just keep moving in a straight line at a constant speed. If I go off-world, then so be it.

The traditional swarm algorithm actually has a few more rules than this, but those rules are rather specific to a single application handling the entire swarm rather than multiple state engines working together.


The best way of using this script that I have found is to create your swarm object... let's say you want to make a school of fish. Create your fish model. Add the script into your fish.

Now comes the tricky part: getting the parameters just right. The swarming behavior does not occur until there are at least 3 of your swarm object within 96 meters of each other. When you have the parameters adjusted and are ready to test your swarm, you must rez at least 3 of the current object. An easy way to do this is to be in edit mode and hit ctrl+d twice. Make sure you take a copy of your object BEFORE you start testing, as incorrectly configured objects tend to fly away very fast! You can also set sandbox to TRUE so they don't get too far away.

Once you have your swarm behaving the way you want it to, make sure you have a timeout set (I generally use 5 minutes) on the swarm object, then create another object that will be the main center point of your swarm. This object will rez new swarm objects every N seconds. This ensures you always have a swarm that is relatively nearby the rezzing object, and in conjunction with the swarm object timeout, ensures you always have a relatively constant number of swarm objects rezzed. The script code for your rezzing object should be something like this (ignore errors... i'm at work right now and don't have access to SL to test this):



code:--------------------------------------------------------------------------------
default {
    state_entry() {
        llSetTimerEvent(20);
    }
    timer() {
        // Rez in a random location within a 10m cube. Don't use 5 in lieu of 5.0 or you could end up with slightly odd results due to the automatic conversion to integer instead of float.
        vector mypos = llGetPos();
        mypos.x += llFrand(10) - 5.0;
        mypos.y += llFrand(10) - 5.0;
        mypos.z += llFrand(10) - 5.0;
        llRezObject("swarm object", mypos, <0,0,0,1>,<0,0,0> );
    }
}
--------------------------------------------------------------------------------


Once you apply this script to your rezzing object, add your swarm object to its contents and let it go. Congratulations, you now have a completely self-maintaining swarm.  

Oh and please please please please please do not create huge swarms with a ton of swarm objects and just let it stay that way. You'll dump the sim's script and physics performance right in the toilet and end up making all your neighbors angry. Just as an FYI I had a swarm of 25 going in Cordova and did not see any slowdown or performance loss at all, but your mileage may vary.

Since it is quite obvious that creating a swarm is not something to be tackled by a non-scripter or even someone who doesn't have much patience, I will be selling my swarm creations soon at my new home in Abbots for a small fee. Since the code is open-source, I will also allow full copy/mod/transfer perms to purchasers.
  



Desconectado Ver perfil del usuario Enviar Mensaje Privado
Descargar Mensaje Volver arriba Página Inferior
Responder Citando  
Mensaje CODIGO DE SWARM 
 
// Swarm script
// by Apotheus Silverman
// with mods from Riptide Ramos
// This script is my implementation of the well-known swarm algorithm
// which can be found in numerous open-source programs.
// Due to the specifics of the SL environment, I have strayed from some
// of the traditional rules slightly. Regardless, the end effect is
// indistiguishable from the original algorithm.

// Configurable parameters

// Determines whether or not to enable STATUS_SANDBOX.
integer sandbox = FALSE;

// Timer length
float timer_length = 0.7;

// Die after this many seconds
integer kill_time = 300;

// How much force to apply with each impulse
float force_modifier = 1.0;

// How much force to apply when repulsed by another like me
float repulse_force_modifier = 0.5;

// How much friction to use on a scale from 0 to 1.
// Note that friction takes effect each timer cycle, so the lower the timer length,
// the more the friction you specify here will take effect, thereby increasing actual
// friction applied.
float friction = 0.6;

// How much to modify rotation damping. Higher numbers produce slower rotation.
float rotation_modifier = 80;

// Does this object "swim" in air or water?
// 2 = air
// 1 = water
// 0 = both
integer flight_mode = 2;

// *** Don't change anything below unless you *really* know what you're doing ***


// Collision function
collide(vector loc) {
    vector mypos = llGetPos();
    float mass = llGetMass();
    // Apply repulse force
    vector impulse = llVecNorm(mypos - loc);
    llApplyImpulse(impulse * repulse_force_modifier * mass, FALSE);
    // Update rotation
    llLookAt(mypos + llGetVel(), mass * 0.5, mass * rotation_modifier);
}

// This function is called whether the sensor senses anything or not
sensor_any() {
    // Die after reaching kill_time
    if (kill_time != 0 && llGetTime() >= kill_time) {
        llDie();
    }

    // Get my position and mass
    vector mypos = llGetPos();

    // Check for air/water breach
    if (flight_mode == 1) {
        // water
        if (mypos.z >= llWater(mypos)) {
            collide(<mypos.x, mypos.y, mypos.z + 0.3> );
        }
    } else if (flight_mode == 2) {
        // air
        if (mypos.z <= llWater(mypos)) {
            collide(<mypos.x, mypos.y, mypos.z - 0.3> );
        }
    }
}


default {
    state_entry() {
        llSay(0, "Fishy spawned.");

        // Sandbox
        llSetStatus(STATUS_SANDBOX, sandbox);
        llSetStatus(STATUS_BLOCK_GRAB, FALSE);

        // Initialize physics behavior
        llSetBuoyancy(1.0);
        llSetStatus(STATUS_PHYSICS, TRUE);
        llSetStatus(STATUS_PHANTOM, FALSE);

        // Initialize sensor
        llSensorRepeat(llGetObjectName(), NULL_KEY, ACTIVE|SCRIPTED, 96, PI, timer_length);
    }


    collision_start(integer total_number) {
        collide(llDetectedPos(0));
    }
    land_collision_start(vector position) {
        vector mypos = llGetPos();
        collide(mypos - llGroundNormal(mypos));
    }

    no_sensor() {
        sensor_any();
    }

    sensor(integer total_number) {
        sensor_any();

        // Populate neighbors with the positions of the two nearest neighbors.
        vector mypos = llGetPos();
        float mass = llGetMass();
        list neighbors = [];
        integer i;
        
        vector v1;
        vector v2;
        float d1 = 100;
        float d2 = 100;

        for (i = 0; i < total_number; i++) {
        vector current_pos = llDetectedPos(i);
        float cur_dist = llVecDist(mypos, current_pos);
        if ( cur_dist < d1 ) {
            // Shift list down, take over top slot.
           d2 = d1;
           v2 = v1;
           d1 = cur_dist;
           v1 = current_pos;
        } else if ( cur_dist < d2 ) {
            // Replace second slot only
           d2 = cur_dist;
           v2 = current_pos;
        }
        }
        
        // Process movement

        // Apply friction
        llApplyImpulse(-(llGetVel() * friction * mass), FALSE);

        // Apply force
        if (llGetListLength(neighbors) == 2) {
            vector neighbor1 = llList2Vector(neighbors, 0);
            vector neighbor2 = llList2Vector(neighbors, 1);
            vector target = neighbor2 + ((neighbor1 - neighbor2) * 0.5);
            vector impulse = llVecNorm(target - mypos);
            llSetForce(impulse * force_modifier * mass, FALSE);
        }

        // Update rotation
        llLookAt(llGetPos() + llGetVel(), mass * 0.5, mass * rotation_modifier);
    }

    on_rez(integer start_param) {
        llResetTime();
    }
}
  



Desconectado Ver perfil del usuario Enviar Mensaje Privado
Descargar Mensaje Volver arriba Página Inferior
Responder Citando  
Mensaje Re: Script De Animales Sociales En SL 
 
Waw...eso lo tengo que probar....!!! Graaaaaacias!!!
  




____________

"I\'ve seen things you people wouldn\'t believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the darkness at Tannhäuser Gate. All those moments will be lost in time like tears in rain."
Desconectado Ver perfil del usuario Enviar Mensaje Privado
Descargar Mensaje Volver arriba Página Inferior
Responder Citando  
Mensaje Re: Script De Animales Sociales En SL 
 
Holaaaa..ya lo he probado... bueno... las particulas se mueven..se comunican..pero no se si es el lag o qué pero que me imaginaba una bandada de pajaros y bueno.. si que se mueven pero mas bien lentitas...
menos mal que tiene una funcion Kill incorporada porque he llenado mi tienda de bolitas que se movian y titilaban..jejeje
..a ver si alguno mas lo probais y comentamos...que me apasiona esto y me gustaria poder ver una bandada de particulas pulular por SL... Smile
  




____________

"I\'ve seen things you people wouldn\'t believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the darkness at Tannhäuser Gate. All those moments will be lost in time like tears in rain."
Desconectado Ver perfil del usuario Enviar Mensaje Privado
Descargar Mensaje Volver arriba Página Inferior
Mostrar mensajes anteriores:
Publicar Nuevo Tema  Responder al Tema  Mensaje de Gracias  Página 1 de 1
 

Usuarios navegando en este Tema: 0 Registrados, 0 Ocultos y 0 Invitados
Usuarios Registrados conectados: Ninguno


 
Lista de Permisos
No puede crear mensajes
No puede responder temas
No puede editar sus mensajes
No puede borrar sus mensajes
No puede votar en encuestas
Puede enviar eventos al Calendario