Scripting cheat sheet :)

Ines Hilz
Ines Hilz Posts: 38 🔥
edited May 2022 in Programming #1

Hi all! I am collecting pieces of script to easily access without going through the docs to copy paste, let me know if this is helpful and feel free to add more snippets in the comments :)


Catch custom Trigger that is sent from Behaviour script and call my_function

global.behaviorSystem.addCustomTriggerResponse("my_custom_Trigger", my_function);


Sends a custom trigger to behaviour scripts in inspektor

global.behaviorSystem.sendCustomTrigger("my_custom_trigger");


This makes the function global and visible for other components to call it

script.api.nameOfMyFunction = function(){   }


Update function

var Update_event = script.createEvent("UpdateEvent");
Update_event.bind(function (eventData)
{
    //do stuff here, happens EVERY FRAME use carefully
});


Bind a function to the tap event.

Other event types: https://lensstudio.snapchat.com/api/Events/

var touchEvent = script.createEvent("TapEvent");
touchEvent.bind(my_function_name_here);


//Delay/wait function

var delayedEvent = script.createEvent("DelayedCallbackEvent");
delayedEvent.bind(function(eventData)
{    
    //Do stuff here // call other functions etc 
});
delayedEvent.reset(2);  // exchange 2 with amount of seconds to delay


ForEach Loop through array

for(var i = 0; i < script.myArray.length; i++){
    script.myArray[i].enabled = true;
} 


Shift arrays:

//shift right ONLY 1 POSITION
script.myArray.unshift(script.myArray.pop());

//shift left ONLY 1 POSITION
script.myArray.push(script.myArray.shift());


//shift array more than 1 position requires a while loop
var i = null;
var shiftAmount = 3;

while (i < shiftAmount){
        i++;
        script.myArray.push(script.myArray.shift());
}


Clear the current material and add a new one

//@Input Asset.Material myMaterial

script.meshVisual.clearMaterials();
script.meshVisual.addMaterial(myMaterial);


Play animated texture on Image

//@input Component.Image 
script.Image.mainMaterial.mainPass.baseTex.control.play(-1,0);


Get a component of a scene Object (here a Image)

script.objectWithImage.getComponent("Component.Image");


Sets a new texture

script.myImage.mainPass.baseTex = script.myTexture;


Checks camera type

if (global.scene.getCameraType() == "back" ){}// oder "front"


Get Child obj from MySceneObj with index starting from 0

var MyScneObject_Child = script.MySceneObj.getChild(0);


Gets a random number between 1 and 10 - You can change the numbers

var randomNumber = Math.floor(Math.random() * 10) + 1;

Comments

  • Ines Hilz
    Ines Hilz Posts: 38 🔥
    edited April 2022 #2

    Create an AudioComponent on this sceneObject and set the audio track + some audio controls

    //@input Asset.AudioTrackAsset myAudio
    
    //create new audio component and set the track
    myAudioComponent = script.getSceneObject().createComponent("Component.AudioComponent");
    myAudioComponent.audioTrack = script.myAudio;
    
    myAudioComponent.play(1);   //play once
    myAudioComponent.play(-1);  //play in a loop
    
    //If it is already playing, stop
    if(myAudioComponent.isPlaying()){
        myAudioComponent.stop(true);
    }
    
    // Set a callback for when the sound stops playing
    myAudioComponent.setOnFinish(function()
    {
        print("sound finished playing");
    });
    
  • Ines Hilz
    Ines Hilz Posts: 38 🔥
    edited May 2022 #3

    Change material properties:

    (in this example i change the color of the Confetti VFX / particle material from the Asset Library, works for every material tho)

    //@input vec3 myParticleColor_Start {"widget":"color"}
    //@input vec3 myParticleColor_End {"widget":"color"}
    //@input Asset.Material Particle_material
    
    script.Particle_material.mainPass.colorStart = script.myParticleColor_Start;
    script.Particle_material.mainPass.colorEnd = script.myParticleColor_End;
    
    //other property example:
    script.Particle_material.mainPass.spawnMaxParticles = 200; 
    

    Hover over the property in the material to get the Property name you need after ...mainPass.

    You can easily animate (most of?) this parameters with a TweenValue helper script if you select : "On Update Callback" -> "Set Material Parameter".

  • Ines Hilz
    Ines Hilz Posts: 38 🔥
    edited May 2022 #4

    .

  • Thank you Ines! This was very helpful

  • Do you have more of these buttons?
    I want new shapes, please ..

    Example

    https://www.snapchat.com/unlock/?type=SNAPCODE&uuid=686b958544f947f8bb382722c47b9e57&metadata=01

  • سعد الفريدي
    سعد الفريدي Posts: 447 🔥🔥🔥

    Hey @Ines Hilz

    Thank You for this.

  • Ines Hilz
    Ines Hilz Posts: 38 🔥

    call a global function from annywhere:

    global.myGlobalFunction();

    The global function:

    global.myGlobalFunction = function(){   
        print("im here");
    }
    
  • Ines Hilz
    Ines Hilz Posts: 38 🔥

    Function to calculate the distance between two Vec3:

    function CalcDistance(Vec1, Vec2){
        distX = Vec2.x - Vec1.x;
        distY = Vec2.y - Vec1.y;
        distZ = Vec2.z - Vec1.z;
        distance = Math.sqrt(distX * distX + distY * distY + distZ * distZ);
        return distance;
    }
    var distance = CalcDistance(Point1, Point2);
    
  • Ines Hilz
    Ines Hilz Posts: 38 🔥

    Scripting snapchat native hints that get translated in all languages:

    Create a dropdown to choose a hint in the inspector:
    ```//@input string hintId {"widget":"combobox","values":[{"label":"Raise your hand","value":"lens_hint_show_your_hand"},{"label":"Aim camera at the sky","value":"lens_hint_aim_camera_at_the_sky"},{"label":"Blow a kiss","value":"lens_hint_blow_a_kiss"},{"label":"Blow a kiss voice changer","value":"lens_hint_blow_a_kiss_voice_changer"},{"label":"Come closer","value":"lens_hint_come_closer"},{"label":"Do not smile","value":"lens_hint_do_not_smile"},{"label":"Do not try with a friend","value":"lens_hint_do_not_try_with_a_friend"},{"label":"Draw with your finger","value":"lens_hint_draw_with_your_finger"},{"label":"Find face","value":"lens_hint_find_face"},{"label":"Find image","value":"lens_hint_find_image"},{"label":"Find marker","value":"lens_hint_find_marker"},{"label":"Find snapcode","value":"lens_hint_find_snapcode"},{"label":"Kiss","value":"lens_hint_kiss"},{"label":"Kiss again","value":"lens_hint_kiss_again"},{"label":"Look around","value":"lens_hint_look_around"},{"label":"Look down","value":"lens_hint_look_down"},{"label":"Look left","value":"lens_hint_look_left"},{"label":"Look right","value":"lens_hint_look_right"},{"label":"Look up","value":"lens_hint_look_up"},{"label":"Make some noise!","value":"lens_hint_make_some_noise"},{"label":"Move your head","value":"lens_hint_move_your_head"},{"label":"Nod your head","value":"lens_hint_nod_your_head"},{"label":"Now kiss","value":"lens_hint_now_kiss"},{"label":"Now open your mouth","value":"lens_hint_now_open_your_mouth"},{"label":"Now raise your eyebrows","value":"lens_hint_now_raise_your_eyebrows"},{"label":"Now smile","value":"lens_hint_now_smile"},{"label":"Open your mouth","value":"lens_hint_open_your_mouth"},{"label":"Open your mouth again","value":"lens_hint_open_your_mouth_again"},{"label":"Open your mouth voice changer","value":"lens_hint_open_your_mouth_voice_changer"},{"label":"Pick a face","value":"lens_hint_pick_a_face"},{"label":"Pick a photo","value":"lens_hint_pick_a_photo"},{"label":"Pick an image","value":"lens_hint_pick_an_image"},{"label":"Raise your eyebrows","value":"lens_hint_raise_your_eyebrows"},{"label":"Raise your eyebrows again","value":"lens_hint_raise_your_eyebrows_again"},{"label":"Raise your eyebrows or open your mouth","value":"lens_hint_raise_eyebrows_or_open_mouth"},{"label":"Raise your eyebrows voice changer","value":"lens_hint_raise_your_eyebrows_voice_changer"},{"label":"Rotate your phone","value":"lens_hint_rotate_your_phone"},{"label":"Say something","value":"lens_hint_say_something"},{"label":"Smile","value":"lens_hint_smile"},{"label":"Smile again","value":"lens_hint_smile_again"},{"label":"Smile voice changer","value":"lens_hint_smile_voice_changer"},{"label":"Swap camera","value":"lens_hint_swap_camera"},{"label":"Tap a surface","value":"lens_hint_tap_a_surface"},{"label":"Tap ground to place","value":"lens_hint_tap_ground_to_place"},{"label":"Tap surface to place","value":"lens_hint_tap_surface_to_place"},{"label":"Tap the ground","value":"lens_hint_tap_ground"},{"label":"Tap!","value":"lens_hint_tap"},{"label":"Tilt your head","value":"lens_hint_tilt_your_head"},{"label":"Try it with a friend","value":"lens_hint_try_friend"},{"label":"Try it with your rear camera","value":"lens_hint_try_rear_camera"},{"label":"Turn around","value":"lens_hint_turn_around"},{"label":"Voice changer","value":"lens_hint_voice_changer"},{"label":"Walk through the door","value":"lens_hint_walk_through_the_door"}]}


    if (!script.initialized) {
    script.hintComponent = script.getSceneObject().createComponent("Component.HintsComponent");
    }
    ```

  • 100%spam
    100%spam Posts: 8
    edited September 2022 #11

    This is not Lens Studio specific but heres a thread on the Javascript basics

    https://support.lensstudio.snapchat.com/hc/en-us/community/posts/360061629432-Basic-JavaScript-Cheet-Sheet

  • Ines Hilz
    Ines Hilz Posts: 38 🔥

    I'm continuing this cheat sheet on GitHub! Feel free to contribute :)
    -> Lens studio JavaScript scripting cheat sheet

  • Ines Hilz
    Ines Hilz Posts: 38 🔥

    Added a bunch of Mini scripts that might be usefull (also the script cheat sheet is still there ; )
    -> Github.com/LensstudioSnippets

  • Bakari Mustafa
    Bakari Mustafa Posts: 174 🔥🔥🔥

    Using machine learning to detect specific objects in the camera view and apply an effect or overlay.

    // load object detection model
    var model = loadModel("model.tflite");
    
    // detect objects
    var objects = detectObjects(model);
    
    // check if a specific object is detected
    if (objects.length > 0) {
      for (var i = 0; i < objects.length; i++) {
        if (objects[i].class == "dog") {
          // apply overlay or effect
          overlay(objects[i].bounds);
        }
      }
    }
    
  • Bakari Mustafa
    Bakari Mustafa Posts: 174 🔥🔥🔥

    Applies different filters on the user's face based on different facial expressions.

    // detect faces
    var face = detectFaces();
    
    // check if a face is detected
    if (face.length > 0) {
       // check the facial expression
       if(face[0].expression.smiling > 0.5){
          // apply a smile filter
          overlay("smile_filter");
       }
       else if(face[0].expression.wink_left > 0.5 || face[0].expression.wink_right > 0.5){
          // apply a wink filter
          overlay("wink_filter");
       }
       else if(face[0].expression.eye_closed_left > 0.5 || face[0].expression.eye_closed_right > 0.5){
          // apply a closed eye filter
          overlay("closed_eye_filter");
       }
    }