# 如何开发一个脚本组件

Script是引擎提供的脚本组件基类,这个类提供了丰富的生命周期函数,所有的自定义脚本都需要继承自这个类。

# 创建一个旋转脚本组件

接下来我们会创建一个名为“Rotate”的脚本组件,在组件内部用到onUpdate生命周期函数,它可以让我们在每一帧渲染前更新实体状态。

提示

脚本组件可重载的生命周期函数,详见

import { Script } from '@tx3d/core';

class Rotate extends Script {

    onUpdate() {

        // TODO:更新实体状态

    }

}
1
2
3
4
5
6
7
8
9
10
11

提示

在函数体内可以通过this.entity获取当前脚本绑定的实体。

# 增加旋转逻辑

想要实现旋转,只要在onUpdate函数内不断改变实体Transform组件的绕Y轴的旋转角度就可以了。

提示

可以通过entity.transform获取Transform组件。

可以使用Transform组件的rotateOnWorldAxis接口实现旋转。

import { MathUtils, Vector3 } from 'three';
import { Script } from '@tx3d/core';

const axis = new Vector3( 0.0, 1.0, 0.0 );
const angle = MathUtils.degToRad( 1.0 );

class Rotate extends Script {

    onUpdate() {

        // 每帧绕Y轴旋转1度
        this.entity.transform.rotateOnWorldAxis( axis, angle );

    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 给实体添加组件

首先我们先加载一个汽车模型,然后把创建好的“Rotate”组件添加到汽车实体上,实现汽车绕Y轴的旋转。

// 加载汽车模型
engine.loadGLTF( 'assets/models/pagani/scene.gltf' ).then( ( entity ) => {

    entity.addComponent( Rotate );

} );
1
2
3
4
5
6
Last Updated: 8/30/2023, 9:51:49 AM