How to access all objects in a single script

Hello,
For example if I have 4 objects (Camera, light, cube, plane) and I want some click event (through raycastFirst).
I am using online editor for creating these.

1- Do i have to give Id or something to each object.
2- Where do I attach the script, to each object or to some global entity.
3- How to change property of one object by clicking other. e.g click on plane to make cube visible etc.

Cheers…

  1. Do you mean accessing the entities at runtime? You can access them by this.app.root.findByName('Camera') or other method in pc.Entity.

  2. It depends your requirement. Just add script component for the entity, and then you can attach the script to certain entity.

  3. You can attach a picker script to the camera:

var Picker = pc.createScript('picker');

Picker.prototype.initialize = function() {
    this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown.bind(this));
};

Picker.prototype.onMouseDown = function(e) {
    var from = this.entity.camera.screenToWorld(e.x, e.y, this.entity.camera.nearClip);
    var to = this.entity.camera.screenToWorld(e.x, e.y, this.entity.camera.farClip);
    var result = this.app.systems.rigidbody.raycastFirst(from, to);

    if (result && result.entity.name === 'plane') {
        var cube = this.app.root.findByName('cube');
        cube.enabled = true;
    }
}

This way is using raycast to select entity, so make sure the plane entity have rigidbody and collision component.

2 Likes

1 Yes, you have to give a tag, id, name or something to each object, so that they can be checked when detected.
For example, you can set a script called stuff with property as tag or id to your entities, and when they’re detected, it goes like

Picker.prototype.onMouseDown = function(e) {
    var from = this.entity.camera.screenToWorld(e.x, e.y, this.entity.camera.nearClip);
    var to = this.entity.camera.screenToWorld(e.x, e.y, this.entity.camera.farClip);
    var result = this.app.systems.rigidbody.raycastFirst(from, to);

//  if (result && result.entity.script.stuff.tag === 'funnyStuff')
//   if (result && result.entity.script.stuff.id === '01') {
    if (result && result.entity.name === 'plane') {
        result.entity.enabled = false;
    }
}

2 You can put your script anywhere you like, but mostly, I put the reycast checker on Camera, so it’s easier to access the camera.
3 For making anentity visible, plz set entity.enabled true. If you wanna make things cooler, plz check
pc.Entity

1 Like