typescript结合three.js

本文介绍使用Three.js和TypeScript创建基本3D游戏场景的方法。包括设置透视相机、WebGL渲染器、光源、坐标轴辅助对象及基础网格材质等元素,并实现物体动画效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import * as THREE from "three";

// https://github.com/pinqy520/three-typescript-starter/blob/master/src/index.ts
class Game
{
    private _scene: THREE.Scene;
    //private _canvas: HTMLCanvasElement;
    private _camera: THREE.PerspectiveCamera;
    private _renderer: THREE.WebGLRenderer;
    private _axis: THREE.AxisHelper;
    private _light: THREE.DirectionalLight;
    private _light2: THREE.DirectionalLight;
    private _material: THREE.MeshBasicMaterial;
    private _box: THREE.Mesh;

    public constructor()
    {
        //this._canvas = <HTMLCanvasElement>document.getElementById(canvasElement);
        this._scene = new THREE.Scene();
        this._camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        this._renderer = new THREE.WebGLRenderer();
        this._axis = new THREE.AxisHelper(10);
        this._light = new THREE.DirectionalLight(0xffffff, 1.0);
        this._light2 = new THREE.DirectionalLight(0xffffff, 1.0);
        this._material = new THREE.MeshBasicMaterial({
            color: 0xaaaaaa,
            wireframe: true
        });
        this._box = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), this._material);
    }

    public createScene(): void
    {
        this._renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(this._renderer.domElement);
        this._scene.add(this._axis);
        this._light.position.set(100, 100, 100);
        this._scene.add(this._light);
        this._light2.position.set(-100, 100, -100)
        this._scene.add(this._light2);
        this._box.position.x = 0.5;
        this._box.rotation.y = 0.5;

        this._camera.position.x = 5;
        this._camera.position.y = 5;
        this._camera.position.z = 5;

        this._camera.lookAt(this._scene.position);
    }

    public animate(): void
    {
        requestAnimationFrame(this.animate);
        this._render();
    }

    private _render(): void
    {
        let timer = 0.002 * Date.now()
        this._box.position.y = 0.5 + 0.5 * Math.sin(timer)
        this._box.rotation.x += 0.1
        this._renderer.render(this._scene, this._camera)
    }
}

window.onload = () =>
{
    let game = new Game();
    game.createScene();
    game.animate();
}


https://stackoverflow.com/questions/35968047/using-webpack-threejs-examples-and-typescript
https://stackoverflow.com/questions/43799041/typescript-error-node-modules-types-three-three-core-d-ts767-24-error-ts230

转载于:https://www.cnblogs.com/feixiangsnail15-12-28/p/8717865.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值