Moving actors

After an actor is added to your scene, either by placing it in the editor or by spawning it at runtime, you may want to move it to a different location or to rotate it. There are two approaches to this:

  • Directly set the new position and rotation on the actor

  • Simulate physics by adding the actor to the physics system with a dynamic or kinematic physics body.

Setting the transform on an actor

If your object should not neceserilly adhere to laws of physics, you can simply set the position and rotation using the actor's position and rotation properties. This will update the rendered transform of the object but it will not update it in the physics world. For that to happen, you also have to apply the actor's transform through the physics system.

In the example below, we have an actor with a rendered and physical representation given by the collision shape. On each frame, we update the actors position according to a speed and direction.

@Actor()
class BallActor extends BaseActor {
    private physics = inject(PhysicsSystem)

    public speed = 0.4
    public direction = new THREE.Vector3(0,0,1)

    private mesh = attach(MeshComponent, {
      mass: 1,
      bodyType: PhysicsBodyType.static,
      object: new PhysicalShapeMesh(
          new SphereGeometry(.2, 20, 10),
          new MeshStandardMaterial({ color: 0xeff542 }),
          new SphereCollisionShape(.2))
    })
    
    onUpdate(deltaTime: number) {
        this.position.addScaledVector(this.direction, this.speed * deltaTime)  
        
        // Also update the physics system so that the physics body is updated
        this.physics.updateActorTransform(this)       
    }
    
}

Last updated