Jump to content

Point'n click + Pathfinding (EasyStar)


Uniform
 Share

Recommended Posts

Hello,

I couldn't really find my issue in the official doc so I though maybe someone could help me.

I am willing to move a cube towars a clicked position on the ground.

It begins after the Action comment. 

Basically I am using the unit vector and translate function to move the box, the first movement is okay because it begins from the center but I don't know how to fix the next ones.

I have attached the source file in case you want to try.

 

Thanks in advance

Uniform

 

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
    <title>Babylon - Getting Started</title>
    <!--- link to the last version of babylon -->
    <script src="babylon.js"></script>
    <style>
        html, body {
            overflow: hidden;
            width   : 100%;
            height  : 100%;
            margin  : 0;
            padding : 0;
        }

        #renderCanvas {
            width   : 100%;
            height  : 100%;
            touch-action: none;
        }
    </style>
</head>
<body>
    <canvas id="renderCanvas"></canvas>
    <script>
        window.addEventListener('DOMContentLoaded', function(){
            // get the canvas DOM element
            var canvas = document.getElementById('renderCanvas');

            // load the 3D engine
            var engine = new BABYLON.Engine(canvas, true);

            // createScene function that creates and return the scene
            var createScene = function(){
                // create a basic BJS Scene object
                    // This creates a basic Babylon Scene object (non-mesh)
			    var scene = new BABYLON.Scene(engine);
				
				scene.clearColor = new BABYLON.Color3(0, 0, 0);

			    // This creates and positions a free camera (non-mesh)
			    var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);

			    // This targets the camera to scene origin
			    

			    camera.position = new BABYLON.Vector3(0,20,0);
			    //camera.setTarget(BABYLON.Vector3.Zero());
			    camera.setTarget(new BABYLON.Vector3(0,-50,0));

			    // This attaches the camera to the canvas
			    camera.attachControl(canvas, true);

			    // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
			    var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0,1,0), scene);
			    light.intensity = 0.8;

			    // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
				var box = BABYLON.Mesh.CreateBox("box", 1.5, scene);
				box.isPickable = false;


				var ball = BABYLON.Mesh.CreateSphere("sphere", 2, 0.5, scene);
				ball.isPickable = false;
				
				
				// Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
			    var ground = BABYLON.Mesh.CreateGround("ground1", 10, 10, 1, scene);

				
				// Materials
				var boxMat = new BABYLON.StandardMaterial("color1", scene);
				boxMat.diffuseColor = new BABYLON.Color3(1.0, 0, 0.3);
				box.material = boxMat;

				var sphereMat = new BABYLON.StandardMaterial("color3",scene);
				sphereMat.diffuseColor = new BABYLON.Color3(0,1,0);
				ball.material = sphereMat;
				
				var groundMat = new BABYLON.StandardMaterial("color2", scene);
				groundMat.diffuseColor = new BABYLON.Color3(0, 0.7, 1.0);
				ground.material = groundMat;
				
				


				// Actions
			    var targetVec = BABYLON.Vector3.Zero();
			    var targetVecNorm = BABYLON.Vector3.Zero();
			    var initVec = box.position;
			    var distVec = 0.0;

				scene.onPointerDown = function (evt, pickResult) {
					if (pickResult.hit && pickResult.pickedMesh == ground) {
						targetVec = pickResult.pickedPoint;
						initVec = box.position;

						targetVecNorm = BABYLON.Vector3.Normalize(targetVec);
						distVec = BABYLON.Vector3.Distance(targetVec,initVec);
						ball.position = targetVec;
						
					}
				}; 				

			    scene.registerBeforeRender(function () {


			    	if (distVec > 0){
			    		distVec -= 0.1;
			    		box.translate(targetVecNorm,0.1,BABYLON.Space.WORLD);
			    		console.log(box.position);
			    		
			    	}

				});

			    return scene;
            }

            // call the createScene function
            var scene = createScene();

            // run the render loop
            engine.runRenderLoop(function(){
                scene.render();
            });

            // the canvas/window resize event handler
            window.addEventListener('resize', function(){
                engine.resize();
            });
        });
    </script>
</body>
</html>

 

babylon.zip

Link to comment
Share on other sites

Hi guys.  We need to playground-up... for this one.

http://playground.babylonjs.com/#22YD8R

I think there MAY be some confusion between a "direction" vector and a "position" vector... happening here.

@iiceman is pretty good at this "targeting stuff", too... so maybe he will visit.  I think he had a hand in THIS demo.  Notice our faithful .moveWithCollisions function... active in line 128.  It is inherited from AbstractMesh, which is Mesh's daddy-o.  :)  It is used often.

The first playground (22yd8r) shows another issue.  After some time clicking-around, the camera/scene does a "shift of position".  (The cyan ground changes position in relation to the cam.)  Possibly, a framework bugski.  :o

Ok, that's all I got. Others may comment, but lots of folks are... out there havin' fun... in the warm California sun  :)

Link to comment
Share on other sites

Thank you guys, I appreciate your support!

 

Hopefully a friend of mine and myself fixed it before seeing your replies.

I put it on the side of my tiredness because this is very silly.

 

Here is a demo for you to try: http://driver-chimpanzee-10603.bitballoon.com/

 

This is the interesting part: http://hpics.li/8bd2d4b

 

 

Here is the source code whenever you feel like implementing it in the playground.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
    <title>Babylon - Getting Started</title>
    <!--- link to the last version of babylon -->
    <script src="babylon.js"></script>
    <style>
        html, body {
            overflow: hidden;
            width   : 100%;
            height  : 100%;
            margin  : 0;
            padding : 0;
        }

        #renderCanvas {
            width   : 100%;
            height  : 100%;
            touch-action: none;
        }
    </style>
</head>
<body>
    <canvas id="renderCanvas"></canvas>
    <script>
        window.addEventListener('DOMContentLoaded', function(){
            // get the canvas DOM element
            var canvas = document.getElementById('renderCanvas');

            // load the 3D engine
            var engine = new BABYLON.Engine(canvas, true);

            // createScene function that creates and return the scene
            var createScene = function(){
                // create a basic BJS Scene object
                    // This creates a basic Babylon Scene object (non-mesh)
			    var scene = new BABYLON.Scene(engine);
				
				scene.clearColor = new BABYLON.Color3(0, 0, 0);

			    // This creates and positions a free camera (non-mesh)
			    var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);

			    // This targets the camera to scene origin
			    

			    camera.position = new BABYLON.Vector3(0,20,0);
			    //camera.setTarget(BABYLON.Vector3.Zero());
			    camera.setTarget(new BABYLON.Vector3(0,-50,0));

			    // This attaches the camera to the canvas
			    camera.attachControl(canvas, true);

			    // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
			    var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0,1,0), scene);
			    light.intensity = 0.8;

			    // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
				var box = BABYLON.Mesh.CreateBox("box", 1.5, scene);
				box.isPickable = false;


				var ball = BABYLON.Mesh.CreateSphere("sphere", 2, 0.5, scene);
				ball.isPickable = false;
				
				
				// Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
			    var ground = BABYLON.Mesh.CreateGround("ground1", 10, 10, 1, scene);

				
				// Materials
				var boxMat = new BABYLON.StandardMaterial("color1", scene);
				boxMat.diffuseColor = new BABYLON.Color3(1.0, 0, 0.3);
				box.material = boxMat;

				var sphereMat = new BABYLON.StandardMaterial("color3",scene);
				sphereMat.diffuseColor = new BABYLON.Color3(0,1,0);
				ball.material = sphereMat;
				
				var groundMat = new BABYLON.StandardMaterial("color2", scene);
				groundMat.diffuseColor = new BABYLON.Color3(0, 0.7, 1.0);
				ground.material = groundMat;
				
				


				// Point'n click logic
			    var targetVec;
			    var targetVecNorm;
			    var initVec;
			    var distVec;

				scene.onPointerDown = function (evt, pickResult) {
					if (pickResult.hit && pickResult.pickedMesh == ground) {
						targetVec = pickResult.pickedPoint;
						ball.position = targetVec.clone();
						
						initVec = box.position.clone();
						distVec = BABYLON.Vector3.Distance(targetVec,initVec);

						targetVec = targetVec.subtract(initVec);
						targetVecNorm = BABYLON.Vector3.Normalize(targetVec);
						
					}
				}; 				

				// Compute translation of the box
			    scene.registerBeforeRender(function () {
			    	if (distVec > 0){
			    		distVec -= 0.1;
			    		box.translate(targetVecNorm,0.1,BABYLON.Space.WORLD);
			    		console.log(box.position);
			    	}
				});
			    return scene;
            }

            // call the createScene function
            var scene = createScene();

            // run the render loop
            engine.runRenderLoop(function(){
                scene.render();
            });

            // the canvas/window resize event handler
            window.addEventListener('resize', function(){
                engine.resize();
            });
        });
    </script>
</body>
</html>

 

Link to comment
Share on other sites

Ah, you already solved it, so no need for me to worry about it anymore, eh? Sweet. It's fairly straight forward as long as you don't need any rotation to align your object with the direction of the movement.

@Wingnut thanks for the notification, always interesting how other people approach a problem you once tried to solve

@Uniform playgrounds are awesome, it's always a good idea to start right with a playground if you have a question. At least that's how I got pretty much all my question answered in almost no time :)

You can search all the playgrounds that have ever been made with the playground search at the documentation page: http://doc.babylonjs.com/playground (thats what wingy used in his post, too)
Or just browser the forum or use google. There are tons of links to playgrounds for almost everything.

Sooo, congratz on solving this. Don't forget to show us the final result when everything is done! :D

Link to comment
Share on other sites

Hi guys.  Is anyone else seeing camera (or floor) "jump"? 

Click low, click high... keep clicking, and eventually you will might see the floor move.  OR, the camera moves.  The floor is not directly under the camera afterwards.  The ground and camera .position is not showing change.  No quaternions defined on ground or camera (which might have caused a ground or camera "tilt").  Possibly, a view matrix problem.

Issue seen in both FF and IE.

Thx for reports.  I did some light testing... no reason discovered, yet.  http://www.babylonjs-playground.com/#1JVKW2#6

Also seen at http://driver-chimpanzee-10603.bitballoon.com/

There seems to be a high-count of greyhound pictures, too, but I don't think that is a demo scene or framework situation.  ;)

Link to comment
Share on other sites

10 hours ago, Wingnut said:

Hi guys.  Is anyone else seeing camera (or floor) "jump"? 

Click low, click high... keep clicking, and eventually you will might see the floor move.  OR, the camera moves.  The floor is not directly under the camera afterwards.  The ground and camera .position is not showing change.  No quaternions defined on ground or camera (which might have caused a ground or camera "tilt").  Possibly, a view matrix problem.

Issue seen in both FF and IE.

Thx for reports.  I did some light testing... no reason discovered, yet.  http://www.babylonjs-playground.com/#1JVKW2#6

Also seen at http://driver-chimpanzee-10603.bitballoon.com/

There seems to be a high-count of greyhound pictures, too, but I don't think that is a demo scene or framework situation.  ;)

The floor moves because the camera is not locked.

Just comment out the line 18: camera.attachControl(canvas, true);

 

Saved here http://www.babylonjs-playground.com/#1JVKW2#7

Link to comment
Share on other sites

2 hours ago, eboo said:

hi

i ve this but not in a PG and with move with collision

https://www.jouer.org/adept-beta.html

try it, if it's your need, check animactor()

 

Very nice but it seems that the character does not go at the place I clicked.

And i have some serious lags when there are several minions following me.

 

By the way the next thing i will try to do is implementing a pathfinding library. http://www.easystarjs.com/

Link to comment
Share on other sites

Nope, I'm not buying that as the reason for the camera "jump".  Go back to #5... and just start a vertical drag.  The camera tilting starts with a "jerk" or "jump", and then I cannot get the camera to return to original position.  But you might not be seeing this... different browser or something. 

But yes, detaching camera control eliminates the problem.  And thus... it is likely that I am accidentally dragging a tiny bit, as I click-around.  During that accidental dragging... I have tilted the camera a tiny bit.  But this "jump" is not a tiny bit. It is an immediate 2-3 degree tilt change.

Just test using only camera drag-tilt.  Hold down left mouse button, and drag up or down.  Camera does an immediate 2-3 degree snap-tilt... not smooth at all.  And it always "jumps" the same direction, no matter if I try up-drag or down-drag.  Once that "snap" happens, it is impossible to put camera back to original starting position.  The camera THINKS it is already directly above the ground.

But, others may not see this.  hmm.  Still studying it.  I think there's an issue with camera.inputs.attached... something weird in the BabylonJS core code... nothing that you or your scene did to cause it.  hmm.  Maybe my computer is going stupid.  :)

http://www.babylonjs-playground.com/#1JVKW2#8

There, I turned off box/sphere moving.  Try a left-mouse-button-drag... up or down.  Does it start with a violent "jerk" or "jump", for you or anyone?  It does for me.  It seems that camera has issues, but there has been recent work happening with our cameras.  Still checking things.

Link to comment
Share on other sites

thanks guys, yeah, with camera at 0, 5, 0.... straight overhead... umm... what?  :)

This is related to the thing where... a camera with gravity applied... won't start falling to the ground... until the camera is "bumped" or "nudged" with a cursor or mouse.

I think there is a camera "epsilon" value that goes into effect... after we "nudge" this camera with the mouse.  Ya know, a gimbal lock prevention epsilon value... that keeps the camera from being precisely polar.  (What did he say?) 

It doesn't go active... until the camera is moved.  That's why Uniform's latest demo (which starts at a higher value than the epsilon value)... shows no jump, but does not allow the camera to get completely polar (directly over 0, 0, 0 origin)  (even when 0, 5, 0 is used in line 8 for cam position).

Someone (I believe it was @Temechon) built a demo/PG where the camera was able to travel smoothly past the polar point and not do an inversion as it did.  I think its laying around here somewhere, but it MAY have been an arcRotate cam. 

All in all, I went searching for that epsilon value... with no success.  It might be in the camera's rotation matrices... as I saw some values in those, but I am not versed in matrix reading.  But I see values in various camera matrix members (at demo RUN-time), and one would think we would see ALL zeros in those matrices.  (Wingnut - feeling-around in the dark, in dangerous alleyways)  heh.  *scratch scratch*

So, this would not be a bug.  It would be an unfortunate and possibly-unavoidable side-effect of overhead-view free-cameras... and frankly, it sucks.  Cam transitions from directly-overhead (view along y axis), to orthogonal (view along x or z axes)... is very common in 3D worlds and needs to happen smooth and nice... and go to 100% overhead (ignore any epsilon values preventing such).  So, I dunno.  Am I over-whiny about this?

It probably belongs in a new topic, so Uniform can get-on with his project.  Poor Uniform is being dragged-into things that he didn't sign-up-for.  :D

For those who don't understand epsilon values, they are tiny little values that keep things from moving to 0 or 100%... and thus avoids divide-by-zero errors.  Think of them as thin pads on the walls and floors of children's play areas... to keep them from 100% smacking into walls or hitting that painful 0% altitude of the concrete floor.  :D   (okay, okay, maybe not a perfect description, but not bad for kiddy-level Wingnut, eh?)

Link to comment
Share on other sites

Little update.

@Wingnut I literraly used your algo http://www.babylonjs-playground.com/#Z3UOX#10

Implemented it in my stuff. Just changed the click detection from DOM event listener to proper babylon scene.onPointerDown function because it can be called 60 times per second.

Before: http://golpher-camel-14043.bitballoon.com/ (click very quickly)

After: http://chess-master-pass-63461.bitballoon.com/ 

 

I do have an issue now tho. When i click very quickly changing the clicked point a bit the mesh is flickering. I believe that I will have to divide the vector into nodes and dynamically update them if the new clicked point is bigger than the distance between the clicked point and the previous point or something like that.

Would be nice to hear from you about that.

 

Oh and for the moment I just stole your algo Wingnut, i will personalize it later but the link has very educational especially because I suck in linear algebra :P

Link to comment
Share on other sites

It's not mine, Uniform.  I think @iiceman coded it.  But ALL code in PG demos is free to use... unless explicitly stated not-so.  Use whatever you need... no problems.  It's good when something found in a playground demo... works for another project.  We all LOVE when that happens.

I don't see mesh flickering at http://chess-master-pass-63461.bitballoon.com/.  I see quick box rotation (to face clicked-point), and I see occasional Firefox garbage collection "stuttering".   I think it works pretty nice.  I'm not sure what you are seeing, sorry.  Feel free to explain further, as wanted.

Link to comment
Share on other sites

On 08/07/2016 at 3:30 PM, Uniform said:

Very nice but it seems that the character does not go at the place I clicked.

it was expected by script. with a "dist" variable to stop avatar running around the exact location.

Link to comment
Share on other sites

@Wingnut Neat! :) Well I was trying to emulate league of legends  movements. It works with nodes, subdivising the path to travel. And it uses epsilon values to see if it needs to calculate all the path again so there is almost no quick movement-rotation for each click like flickering. 

 

@eboo Got it :)

Link to comment
Share on other sites

4 hours ago, iiceman said:

Very cool, good job Uniform! What kind of game are you making, if I my ask? :)

This is a dota based game.

But I am not sure if my way to map the terrrain is the most effective one. Do you know any other way by any chance?

I am using an abstract mesh to go over all the terrain every frame and depending if it is colliding with something build an abstract collision layer in the form of a matrix.

Link to comment
Share on other sites

8 hours ago, iiceman said:

That sounds indeed like it would cost a lot of performance. I don't have a better approach right away. Why do you have to do it every frame? Does the terrain change?

Nope but the objects moving on the terrain affect the terrain collision mapping. Oh and I don't calculate every frame, I calculate when you click. 

I am wondering if creating 2 Abstract mesh to map the terrain 2 times faster would really increase performace. By the way I have no performance issues so far.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...