how to render alphabets in 2D using threejs

爱⌒轻易说出口 提交于 2019-12-24 17:27:59

问题


I'm making a 2d game, where blocks are falling down ( tetris style). I need to render alphabets on these blocks. This is how I am creating blocks:

	var geometry = new THREE.BoxGeometry( this.BLOCK_WIDTH, this.BLOCK_WIDTH, 4 );
	var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

	this.blocks = [];

	for (var i = 0; i < rows * columns; i++) {
		cube = new THREE.Mesh( geometry, material );
		cube.visible = false;
		cube.letter = letterGenerator.getNextLetter();
		this.blocks[i] = cube;

		scene.add( this.blocks[i] );
	};

As you can see, all blocks will look exactly alike except for the fact, that they will have a different alphabet associated with them. In my update(), I move the block, left/right or down. When I do so, block position will be updated and obviously the alphabet should be rendered accordingly.

How should I go about rendering alphabets on these blocks ?

EDIT: I am using WebGLRenderer.


回答1:


You can get the screen position of each block (your "cube" variable above) that you want to paint text on and use HTML to paint text at that screen location over each block. Using HTML to make a text sprite like this is discussed here:

https://github.com/mrdoob/three.js/issues/1321

You can get the screen position for your "cube" above like so:

var container = document.getElementById("idcanvas");
var containerWidth = container.clientWidth;
var containerHeight = container.clientHeight;
var widthHalf = containerWidth / 2, heightHalf = containerHeight / 2;
var locvector = new THREE.Vector3();
locvector.setFromMatrixPosition(cube.matrixWorld);
locvector.project(your_camera); //returns center of mesh
var xpos = locvector.x = (locvector.x * widthHalf) + widthHalf; //convert to screen coordinates
var ypos = locvector.y = -(locvector.y * heightHalf) + heightHalf;

You'll have to update the HTML for cube movement.

Another approach is to create specific textures with the text you want and apply each texture as a material to the appropriate cube.



来源:https://stackoverflow.com/questions/34940113/how-to-render-alphabets-in-2d-using-threejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!