跳到主要内容

调用引擎 API

编写 PlayCanvas 脚本时,使用的是 PlayCanvas Engine API。本页介绍脚本中最常用的关键类与模式。

脚本开发的关键类​

脚本上下文​

每个脚本都能访问以下核心对象:

this.app // The main application (AppBase)
this.entity // The entity this script is attached to
important

this.app 和 this.entity 仅在脚本实例的方法(如 initialize、update)中有效。进一步了解 JavaScript 的 this 关键字。

核心类​

AppBase:应用。

// Common app operations
this.app.fire('game:start');
const player = this.app.root.findByName('Player');
const texture = this.app.assets.find('logo', 'texture');

Entity:场景中的对象。

// Common entity operations
this.entity.setPosition(0, 5, 0);
this.entity.rotate(0, 90, 0);
const child = this.entity.findByName('Weapon');

Component:为实体添加功能。

// Accessing components
const camera = this.entity.camera;
const light = this.entity.light;
const rigidbody = this.entity.rigidbody;
const sound = this.entity.sound;

数学类​

导入以下类进行计算与变换:

import { Vec3, Quat, Color } from 'playcanvas';

const position = new Vec3(0, 5, 0);
const rotation = new Quat();
const red = new Color(1, 0, 0);

常用脚本模式​

查找实体​

// By name (searches entire hierarchy)
const player = this.app.root.findByName('Player');

// By tag (returns array)
const enemies = this.app.root.findByTag('enemy');

// Relative to current entity
const weapon = this.entity.findByPath('Arms/RightHand/Weapon');

使用资源​

// Find and load assets
const sound = this.app.assets.find('explosion', 'audio');
sound.ready(() => {
this.entity.sound.play('explosion');
});
this.app.assets.load(sound);

事件与通信​

// Fire application events
this.app.fire('player:died', this.entity);

// Listen for events
this.app.on('game:start', this.onGameStart, this);

进一步学习​

提示

IDE 支持:使用 VS Code 扩展,在编写脚本时获得自动补全和行内文档。