How internally conversion of 2d to 3d?

Hello Members,
In my project , I have 3d map and 3d car, When I clicked on map that car is moving on the map. That Click Event only gives X & Y. Then How three.js internally convert X Y to X Y Z position on the map. See Video . Now I want give manually X & Y position not by using Click. Then How I can convert that position.

2d to 3d 1

Thank You…!
Sandip

Check out the raycaster.

@looeee already used, but now I want to give manually input. Input will come from database. On mouse click its working fine see video

Yep, you’ll use Raycaster to create a ray from the point that you get from the database (instead of using the point from a click event). If you look at Raycaster that looee linked, there’s lots of examples.

@trusktr @looeee
See Code

PatrolJS Demo
<style>
	body {
		font-family: Arial;
		background-color: #000;
		color: #fff;
		margin: 0px;
		overflow: hidden;
	}

	.info {
		padding: 10px;
		width: 100%;
		position: absolute;
		background-color: rgba(255, 0, 0, 0.5);
		font-size: 14px;
	}

	.info h1 {
		padding: 0;
		margin: 0;
	}

</style>

<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
	<script>

		var container;

		var camera, scene, renderer, controls;

		var raycaster, intersectedObject;

		var mouse = new THREE.Vector2();

		var startTime	= Date.now();

		var windowHalfX = window.innerWidth / 2;
		var windowHalfY = window.innerHeight / 2;

		var lastFrameTime = 0;
		var maxFrameTime = 0.03;
		var elapsedTime = 0;
		var player = new THREE.Object3D();
		var player1 = new THREE.Object3D();
		var level;
		 var movePosition;

		init();
		animate();

		var  target;

		var playerNavMeshGroup;

		var calculatedPath = null;

		var pathLines;
		

		function init() {
			
			/* setTimeout(function(){
				console.log("comming")
				onDocumentMouseClick (1070,281);
			},10000); */
			movePosition=player;
			container = document.createElement( 'div' );
			document.body.appendChild( container );

			camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
			camera.position.x = -10;
			camera.position.y = 14;
			camera.position.z = 10;

			scene = new THREE.Scene();

			

			var directionalLight = new THREE.DirectionalLight( );
			directionalLight.position.set( 0, 0.5, 0.5 );
			scene.add( directionalLight );

			var objLoader = new THREE.OBJLoader();

			objLoader.load( 'meshes/mesh/Mesh/ska6.obj', function( object ) {
			//	object.position.y = 1000;
			    object.traverse(function (node) {
					if (node.type === 'Mesh') level = node;
				});
			    scene.add(level);
			});

			objLoader.load( 'meshes/mesh/Mesh/mergeNav4.obj', function( object ) {
				var navmesh;
				object.traverse(function (node) {
					if (node.type === 'Mesh') navmesh = node;
				});

				var geometry = new THREE.Geometry();
				geometry.fromBufferGeometry(navmesh.geometry);
				var zoneNodes = patrol.buildNodes(geometry);

				patrol.setZoneData('level', zoneNodes);

				Object.assign(navmesh.material, {
					color: 0x009688,
					opacity: 0.5,
					transparent: true
				});

				scene.add(navmesh);

			// Set the player's navigation mesh group
				playerNavMeshGroup = patrol.getGroup('level', player1.position);

			}); 
			

			
			var loader = new THREE.OBJLoader();

			// load a resource
			loader.load(
				// resource URL
				'meshes/mesh/Mesh/car/truck.obj',
				// called when resource is loaded
				
				function ( object ) {
					object.scale.set(0.2,0.2,0.2);
				//	object.position.set(-4.5, 5.3, 5.6);
					 player.add(object);
					 object.traverse( function ( child ) {
                         if ( child instanceof THREE.Mesh ) {
                              //child.material.ambient.setHex(0xFF0000);
                              child.material.color.setHex(0xFF0000);
                             }
                         } );
					 
				},
				
			);
			var loader1 = new THREE.OBJLoader();

			// load a resource
			loader1.load(
				// resource URL
				'meshes/mesh/Mesh/car/car.obj',
				// called when resource is loaded
				
				function ( object ) {
					object.scale.set(0.2,0.2,0.2);
				//	object.position.set(-4.5, 5.3, 5.6);
					 player1.add(object);
					 object.traverse( function ( child ) {
                         if ( child instanceof THREE.Mesh ) {
                              //child.material.ambient.setHex(0xFF0000);
                              child.material.color.setHex(0xFF0000);
                             }
                         } );

				},
				
			);
	
	        // Add test sphere 
	        
			//var geometry = new THREE.SphereGeometry( 0.5, 40, 40 );
			var material = new THREE.MeshBasicMaterial( {color: 0xff0000} );
			player = new THREE.Mesh(  material );
			scene.add( player );

			player.position.set(-4.5, 5, 5.7);
			
			player1 = new THREE.Mesh(  material );
			scene.add( player1 );

			player1.position.set(-5.5, 5, 5.7);
			
			
			// end point
			geometry = new THREE.BoxGeometry( 0.3, 0.3, 0.3 );
			var material = new THREE.MeshBasicMaterial( {color: 0xff0000} ); 
			target = new THREE.Mesh( geometry, material );
			scene.add( target );

			target.position.copy(player1.position);
		//	console.log("target.position ");
		//	console.log(target.position)

			// background
			renderer = new THREE.WebGLRenderer();
			renderer.setPixelRatio( window.devicePixelRatio );
			renderer.setSize( window.innerWidth, window.innerHeight );
			renderer.setClearColor(0xffffff);
			container.appendChild( renderer.domElement );

			raycaster = new THREE.Raycaster();
			
			document.addEventListener( 'click', getCords, false );
			document.addEventListener( 'contextmenu', onDocumentMouseDblClick, false );
			window.addEventListener( 'resize', onWindowResize, false );

			controls = new THREE.OrbitControls( camera );
			controls.damping = 0.2;

		}
		
		function getCords(event){
			onDocumentMouseClick(event.clientX,event.clientY)
		}
		function onDocumentMouseDblClick (event) {
			movePosition=player1;
			// event.preventDefault();
			console.log("event.clientX = "+event.clientX+" event.clientY = "+event.clientY);

			mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
			mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
			

			camera.updateMatrixWorld();

			raycaster.setFromCamera( mouse, camera );

			var intersects = raycaster.intersectObject( level );

			if ( intersects.length > 0 ) {
				var vec = intersects[0].point;
				target.position.copy(vec);

				// Calculate a path to the target and store it
				calculatedPath = patrol.findPath(player1.position, target.position, 'level', playerNavMeshGroup);
			

				if (calculatedPath && calculatedPath.length) {

					if (pathLines) {
						scene.remove(pathLines);
					}

					var material = new THREE.LineBasicMaterial({
						color: 0x0000ff,
						linewidth: 2
					});
					var geometry = new THREE.Geometry();
					geometry.vertices.push(player1.position);
				//	console.log("player.position "+player1.position)
					//console.log(player1.position)
					


					// Draw debug lines
					for (var i = 0; i < calculatedPath.length; i++) {
						geometry.vertices.push(calculatedPath[i].clone().add(new THREE.Vector3(0, 0.2, 0)));
					}

					pathLines = new THREE.Line( geometry, material );
					scene.add( pathLines );

					// Draw debug cubes except the last one. Also, add the player position.
					var debugPath = [player1.position].concat(calculatedPath);

					for (var i = 0; i < debugPath.length - 1; i++) {
						geometry = new THREE.BoxGeometry( 0.3, 0.3, 0.3 );
						var material = new THREE.MeshBasicMaterial( {color: 0x00ffff} );
						var node = new THREE.Mesh( geometry, material );
						node.position.copy(debugPath[i]);
						pathLines.add( node );
					}
				}
			}
		}
		
		function onDocumentMouseClick (x,y) {
			 movePosition=player;
			var mouse = new THREE.Vector2();
			// event.preventDefault();
			//console.log("event.clientX = "+event.clientX+" event.clientY = "+event.clientX);
			 mouse.x = ( x / window.innerWidth ) * 2 - 1;
			 mouse.y = - ( y / window.innerHeight ) * 2 + 1;
			console.log("mouse.x = "+mouse.x+" mouse.y = "+mouse.y)

			camera.updateMatrixWorld();

			raycaster.setFromCamera( mouse, camera );

			var intersects = raycaster.intersectObject( level );

			if ( intersects.length > 0 ) {
				var vec = intersects[0].point;
				target.position.copy(vec);

				// Calculate a path to the target and store it
				calculatedPath = patrol.findPath(player.position, target.position, 'level', playerNavMeshGroup);

				if (calculatedPath && calculatedPath.length) {

					if (pathLines) {
						scene.remove(pathLines);
					}

					var material = new THREE.LineBasicMaterial({
						color: 0x0000ff,
						linewidth: 2
					});
					var geometry = new THREE.Geometry();
					geometry.vertices.push(player.position);
					console.log("player.position "+player.position)
					console.log(player.position)


					// Draw debug lines
					for (var i = 0; i < calculatedPath.length; i++) {
						geometry.vertices.push(calculatedPath[i].clone().add(new THREE.Vector3(0, 0.2, 0)));
					}

					pathLines = new THREE.Line( geometry, material );
					scene.add( pathLines );

					// Draw debug cubes except the last one. Also, add the player position.
					var debugPath = [player.position].concat(calculatedPath);

					for (var i = 0; i < debugPath.length - 1; i++) {
						geometry = new THREE.BoxGeometry( 0.3, 0.3, 0.3 );
						var material = new THREE.MeshBasicMaterial( {color: 0x00ffff} );
						var node = new THREE.Mesh( geometry, material );
						node.position.copy(debugPath[i]);
						pathLines.add( node );
					}
				}
			}
		}

		function onWindowResize() {
			windowHalfX = window.innerWidth / 2;
			windowHalfY = window.innerHeight / 2;

			camera.aspect = window.innerWidth / window.innerHeight;
			camera.updateProjectionMatrix();

			renderer.setSize( window.innerWidth, window.innerHeight );
		}

		function animate() {
			
            var currTime = window.performance.now();
            var delta = (currTime - lastFrameTime) / 1000;
            var dTime = Math.min(delta, maxFrameTime);
            elapsedTime += delta;
            lastFrameTime = currTime;
            tick(dTime);
			requestAnimationFrame( animate );
			render();
		}

		function tick(dTime) {
			var moveEntityPosition = movePosition;
			if (!level) {
				return;
			}

			var speed = 5;

			var targetPosition;

			if (calculatedPath && calculatedPath.length) {
				targetPosition = calculatedPath[0];

				var vel = targetPosition.clone().sub(moveEntityPosition.position);

				if (vel.lengthSq() > 0.05 * 0.05) {
					vel.normalize();

					// Mve player to target
					moveEntityPosition.position.add(vel.multiplyScalar(dTime * speed));
				}
				else {
					// Remove node from the path we calculated
					calculatedPath.shift();
				}
			}
		}  

		function render() {
			camera.lookAt( scene.position );
			camera.updateMatrixWorld();

			renderer.render( scene, camera );

		}

	</script>



</body>

This is the most confusing part. Could you clarify what it means?
From my point of view, “manually” is when you have input(s) for coordinates and type data in it. But then you say about input from database and this contradicts the previous statement.

Further, you don’t tell, what format of data will come from the database. Is it intended to be used as THREE.Vector2() or THREE.Vector3(). Is this coordinates of click on the screen? If so, is the camera position taken into account?

Instead, you just upload your project awhole and offer to write all the things for you.

@prisoner849
About My Project 3d navigation map. In that 3d map(navMesh) & 3d cars .obj file is there. For test purpose I done sample project in that on Mouse click car is moving on the road. Mouse click event take X & Y coordinate of the current scree. Its working fine.
Now I merged my sample project in real project in that 3rd party will give only X & Y then how to pass that X & Y. Previously I was taking current window screen . I know my English is weak, I hope u understood my problem. See Video

Those X & Y from the third party software, what are they?
Could you illustrate with pictures?
Kind of: “I have coordinates x, y in a such format. On the screen they are at this position [picture]. I want to do this to have that as a result”. Just in case, this is an example of how you could explain, not an exact plan.

when on real road car is moving that time they will send x & y to DB, then I have to move car(.obj) according to DB values.

@looeee I dont want to use mouse click, I will pass the value and car will move along the map

Where will be your car, when it should go under a bridge, but you have only coordinates of x and y?

@prisoner849 without mouse click , car should be go from Source to Destination. This car moves after clicking. But It should go without click

2d to 3d 2

So instead of writing your raycaster logic in a click handler, write it in the callback for when you receive the database data.

@trusktr that is I dont know can u give some code or example. I am totally new in JS

How do you get the database data? Can you post just that piece of code?

@trusktr
java code
@RequestMapping(value = “tagLocation”, method = RequestMethod.POST)
public JSONObject getEntityDetailsByTagMacId(@RequestHeader(“mapId”) final String mapId,
@RequestHeader(“tagMacId”) final String tagMacId, @RequestHeader(“xCoordinate”) final String xCoordinate,
@RequestHeader(“yCoordinate”) final String yCoordinate) {
logger.info("mapId " + mapId);
logger.info("tagMacId " + tagMacId);
logger.info("xCoordinate " + xCoordinate);
logger.info("yCoordinate " + yCoordinate);
JSONObject jsonObject = new JSONObject();
if (!NumberUtils.isNumber(xCoordinate) && !NumberUtils.isNumber(yCoordinate)) {
jsonObject.put(“responseCode”, 0);
jsonObject.put(“errorMessage”, “Invalid Co-Ordinates”);
return jsonObject;
}
if (StringUtils.isNotBlank(tagMacId)) {
TblEntity tblEntity = entityService.getByTagMacId(tagMacId);
if (tblEntity == null) {
jsonObject.put(“responseCode”, 0);
jsonObject.put(“errorMessage”, “Tag not Assigned”);
}
else {
MapEntityTo jsonto = entityService.getEntityByTagMacIdReturnMapEntityTo(tagMacId, mapId, xCoordinate, yCoordinate);
jsonto.setNote(“Sample Text”);
jsonObject.put(“responseCode”, 1);
jsonObject.put(“responseData”, jsonto);
if (CollectionUtils.isNotEmpty(groupsList)) {
boolean isGroupFound = groupsList.stream()
.anyMatch(group -> group.getGroupCode().equalsIgnoreCase(tblEntity.getTblGroup().getGroupCode()));
if (isGroupFound) {
entityService.pushEntityLocation(jsonObject);
}
}
else {
entityService.pushEntityLocation(jsonObject);
}
}
}
else {
jsonObject.put(“responseCode”, 0);
jsonObject.put(“errorMessage”, “invalide parameter”);
}
return jsonObject;
}

sending data
send data

Okay, the Java code doesn’t matter. Where is the JavaScript code that is getting the data from the Java server?

If there is no such code yet, then you should look at using fetch to get the data. Then come back here once you’ve figure that out.

1 Like

Here’s a better article on the Fetch API. In particular, you’ll need to use the .json() method.

Note, fetch() may not work in older IE browsers. Here’s a polyfill. Or you can use the older XMLHttpRequest, or jQuery.ajax.

Once you know how to get data, then you can use the X,Y value from the database after you’ve received the data.

@trusktr yet I did not implement in java script, previous 2d map is there now 3d map. But 3d map has X Y Z and they give only X Y. What should I write in JavaScript to fetch data from Java.