Camera controls are opposite to what they should be. Why? - graphics

I am creating a playable maze in Three.js. All the objects —the floor, the ceiling and the walls— have been placed within positive X and Z axises. The camera is placed like this:
camera = new THREE.PerspectiveCamera(45,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(0, 0.25, 0);
// The camera is placed pointing to the nearest open path from the
// initial position. Check mazeGenerator.js for the reference of
// "coordinates".
if(grid[1][0] == coordinates.W)
{
camera.lookAt(new THREE.Vector3(1, 0.25, 0));
}
else
{
camera.lookAt(new THREE.Vector3(0, 0.25, 1));
}
and it moves like that:
function keyboardCheck()
{
var movementSpeed = 0.02;
var rotationSpeed = 0.03;
if(keyboard.pressed('w') || keyboard.pressed('up'))
{
camera.translateZ(-movementSpeed);
}
if(keyboard.pressed('a') || keyboard.pressed('left'))
{
camera.rotateY(rotationSpeed);
}
if(keyboard.pressed('d') || keyboard.pressed('right'))
{
camera.rotateY(-rotationSpeed);
}
}
If I place the camera without the lookAt function, it seems that it faces [0, 0, 0], but of course what I wanted to do was help the player a little bit by making the camera face the nearest open path possible.
In order to make it move forward, I have to decrement Z, because otherwise when you hit the "move forward" key it goes backwards. This makes me think that even though I am telling the camera to look at a certain direction, the object's Z axis is opposite to the world's Z axis.
The question itself is: why is this happening?
Thank you very much in advance.
https://github.com/MikelAlejoBR/3D-Maze-95/tree/0.4
https://github.com/MikelAlejoBR/3D-Maze-95/issues/8

The camera is looking down its negative-z axis, so to move forward, do this:
camera.translateZ( - distance );
All other objects are considered to be looking in the direction of their positive-z axis, so to move other objects forward, you would use
object.translateZ( distance );
three.js r.85

Related

libgdx draw text via project draws twice?

I try to draw 2D texts for my 3D world objects with libgdx's camera.project function but have a weird problem.
See the pics below:
As you can see in the pictures, all is well in picture 1 but when I turn around 180 degrees the ball's name (codename 1) is be drawing the blank space also (picture 2). I couldn't get what the problem is and after hours of thinking decided to ask here.
Please help me.
My code is:
public static void drawNames(){
TheGame.spriteBatch.begin();
for(int i = 0; i < TheGame.playerMap.size; i++){
Player ply = TheGame.playerMap.getValueAt(i);
if(!ply.isAlive)
continue;
TheGame.tmpVec.set(ply.getPos().x, ply.getPos().y, ply.getPos().z);
TheGame.cam.project(TheGame.tmpVec);
TheGame.fontArialM.draw(TheGame.spriteBatch, ply.name, TheGame.tmpVec.x, TheGame.tmpVec.y, 0, Align.center, false);
}
TheGame.spriteBatch.end();
}
This is because if you project something that is behind the camera it still gets valid screen coordinates from the project method.
Consider the following that prints the screen coordinates of two world coordinates
PerspectiveCamera camera = new PerspectiveCamera(60, 800, 600);
camera.position.set(0, 0, -10);
camera.lookAt(0, 0, 0);
camera.update();
Vector3 temp = new Vector3();
Vector3 p1 = new Vector3(1, 0, 10); // This is in front of the camera, slightly to the right
Vector3 p2 = new Vector3(0, 0, -100); // This is behind of the camera
camera.project(temp.set(p1));
System.out.println("p1 is at screen " + temp);
if (camera.frustum.pointInFrustum(p1))
System.out.println("p1 is visible to the camera");
else
System.out.println("p1 is not visible to the camera");
camera.project(temp.set(p2));
System.out.println("p2 is at screen " + temp);
if (camera.frustum.pointInFrustum(p2))
System.out.println("p2 is visible to the camera");
else
System.out.println("p2 is not visible to the camera");
In your code, before rendering the text you need to check if the ply.getPos() vector is visible to the camera, and only render the text if it is.
if (TheGame.cam.frustum.pointInFrustum(ply.getPos()) {
TheGame.tmpVec.set(ply.getPos().x, ply.getPos().y, ply.getPos().z);
TheGame.cam.project(TheGame.tmpVec);
TheGame.fontArialM.draw(TheGame.spriteBatch, ply.name, TheGame.tmpVec.x, TheGame.tmpVec.y, 0, Align.center, false);
}
Note that there are other ways to cull things behind the camera that might be more efficient for you.

collision with wall isn't accurate

So I'm trying to make a ball hit the wall and bounce off it just like pong game. but for some reason when ball thinks the canvas is smaller that it actually is.
here is my onDraw code:
canvasWidth = canvas.getWidth();
canvasHeight = canvas.getHeight();
if (flag) {
x = (int) canvasWidth;
y = (int) canvasHeight;
}
else
{
if (goingRight)
x=x+5;
else
x=x-5;
if (goingDown)
y=y+5;
else
y=y-5;
}
canvas.drawBitmap(ball,x/2,y/2,null);
if (x>canvasWidth)
goingRight=false;
else if (x<0)
goingRight=true;
if (y>canvasHeight)
goingDown=false;
else if (y<0)
{
goingDown=true;
}
flag=false;
Couldn't find a fix for it. anyone knows what is the problem?
Probably because you draw your ball at half x and half y.
canvas.drawBitmap(ball,x/2,y/2,null);
I think you want draw the ball not on top/left corner of the bitmap but on center.
Is not tested ! Try somthing as...
canvas.drawBitmap(ball,x - (ball.getWidth()/2),y - (ball.getHeight()/2),null);

Moving one end of a Phaser.Graphics line

For a project I'm trying to draw a moving line in Phaser. I initially drew it using game.debug.geom(line), but that is not really the right way to do it, since it doesn't allow for styling, and because the debugger takes a toll in performance.
Reading the docs, it seems to me that the way to do it would be with a Phaser.Graphics object, but I haven't been able to get it to work. As an example, I tried making a line move as the hand of a clock, with one end fixed and the other moving around it.
I thought it would be fine to create the Graphics object in the middle and then in update use reset to clear it and bring it back to the center, and then lineTo to make the rest of the line. But instead what I get is a line coming outwards from the centre, and then a ring.
Picture for sadness:
I made a pen with my attempts. The code is repeated below. What I would like to have is a line (lines?) coming from the center of the circle to the points in the circumference.
Is a Graphics object the best way to do that? How do I do it?
Demo.prototype = {
create: function() {
this.graphics = game.add.graphics(
game.world.centerX,
game.world.centerY
);
this.graphics.lineStyle(2, 0xffd900);
this.counter = 0;
this.step = Math.PI * 2 / 360;
this.radius = 80;
},
update: function() {
this.graphics.reset(
this.game.world.centerX,
this.game.world.centerY
);
var y = this.radius * Math.sin(this.counter);
var x = this.radius * Math.cos(this.counter);
this.graphics.lineTo(x, y);
this.counter += this.step;
}
};
You may want to check out this Phaser game called Cut It (not my game btw, found it here).
It also draws a variable length dotted line by cleverly using the Phaser.TileSprite, and then changing its width.
TileSprite draws a repeating pattern, and you can use this to draw a line by drawing one bitmap of a linepart segment, use that as background of the TileSprite and make the height of the TileSprite the same as the height of the bitmap.
You can take a look at the game's source code, it's compressed and minified but still somewhat readable. You can look for the variable called cut_line.
I finally understood that the coordinates taken by the Phaser.Graphics object are local, respective to the object's internal coordinate system. Using moveTo(0, 0) has the desired result of moving the object's drawing pointer back to its origin (and not, as I initially thought, to the origin of the game world). Using reset(0, 0), on the other hand, would have the effect of moving the object's origin to the world's origin.
As for deleting the previous lines, the only method I've found is to manually clear the object's graphicsData Array (short of calling destroy() and creating an entirely new object, which is probably not a very good idea).
Replacing the code in the original question with this does the trick:
Demo.prototype = {
create: function() {
this.graphics = game.add.graphics(
game.world.centerX,
game.world.centerY
);
this.graphics.lineStyle(2, 0xffd900);
this.counter = 0;
this.step = Math.PI * 2 / 360;
this.radius = 80;
},
update: function(){
// Erases the previous lines
this.graphics.graphicsData = [];
// Move back to the object's origin
// Coordinates are local!
this.graphics.moveTo( 0, 0 );
var y = this.radius * Math.sin(this.counter);
var x = this.radius * Math.cos(this.counter);
this.graphics.lineTo(x, y);
this.counter += this.step;
}
};

Rotating object relative to mouse position

At the moment I'm using the dot product of the mouse position and (0, 1) to generate radians to rotate an object, in three.js
Code below, works ok but the object 'jumps' because the radian angle skips from positive to negative when the clientX value goes between window.innerWidth / 2
onDocumentMouseMove : function(event) {
// rotate circle relative to current mouse pos
var oldPos = new THREE.Vector2(0, 1);
Template.Main.mouseCurrPos = new THREE.Vector2((event.clientX / window.innerWidth ) * 2 - 1, - (event.clientY / window.innerHeight) * 2 + 1);
Template.Main.mouseCurrPos.normalize();
//Template.Main.projector.unprojectVector(Template.Main.mouseCurrPos, Template.Main.scene);
var angle = oldPos.dot(Template.Main.mouseCurrPos);
Template.Main.mousePrevPos.x = event.clientX;
Template.Main.mousePrevPos.y = event.clientY;
if (event.clientX < window.innerWidth / 2) {
Template.Main.circle.rotation.z = -angle;
}
else {
Template.Main.circle.rotation.z = angle;
}
console.log(Template.Main.circle.rotation.z);
}
However if I add this to assign the value to oldPos:
if (event.clientX < window.innerWidth / 2) {
oldPos = new THREE.Vector2(0, -1);
}
else {
oldPos = new THREE.Vector2(0, 1);
}
Then the "jumping" goes but the effect of rotation is inverted when the mouse is on the left of the window.
I.e. mouse going up rotates anti-clockwise and vice-versa which is not desired.
It's frustrating.
Also if I keep the oldPos conditional assignment and leave out the conditional negation of the angle instead, the jumping comes back.
You can see a demo here: http://theworldmoves.me/rotation-demo/
Many thanks for any tips.
Why are you using the result of the dot product as the angle (radians)? The dot product gives you the cosine of the angle (times the magnitude of the vectors, but these are a unit vector and a normalized vector, so that doesn't matter).
You could change your angle computation to
var angle = Math.acos(oldPos.dot(Template.Main.mouseCurrPos));
However, you may get the wrong quadrant, since there can be two values of theta that satisfy cos(theta) = n. The usual way to get the angle of a vector (origin to mouse position) in the right quadrant is to use atan2():
var angle = Math.atan2(Template.Main.mouseCurrPos.y,
Template.Main.mouseCurrPos.x);
This should give the angle of the mouse position vector, going counterclockwise from (1, 0). A little experimentation can determine for sure where the zero angle is, and which direction is positive rotation.

How to remove the effect of light / shadow on my model in XNA?

I am developing a small game and I would draw a field-ground(land) with a repeated texture. My problem is the rendered result. This gives the impression of seeing everything around my cube looked as if a light shadow.
Is it possible to standardize the light or remove the shadow effect in my drawing function?
Sorry for my bad english..
Here is a screenshot to better understand my problem.
Here my code draw function (instancing model with vertexbuffer)
// Draw Function (instancing model - vertexbuffer)
public void DrawModelHardwareInstancing(Model model,Texture2D texture, Matrix[] modelBones,
Matrix[] instances, Matrix view, Matrix projection)
{
if (instances.Length == 0)
return;
// If we have more instances than room in our vertex buffer, grow it to the neccessary size.
if ((instanceVertexBuffer == null) ||
(instances.Length > instanceVertexBuffer.VertexCount))
{
if (instanceVertexBuffer != null)
instanceVertexBuffer.Dispose();
instanceVertexBuffer = new DynamicVertexBuffer(Game.GraphicsDevice, instanceVertexDeclaration,
instances.Length, BufferUsage.WriteOnly);
}
// Transfer the latest instance transform matrices into the instanceVertexBuffer.
instanceVertexBuffer.SetData(instances, 0, instances.Length, SetDataOptions.Discard);
foreach (ModelMesh mesh in model.Meshes)
{
foreach (ModelMeshPart meshPart in mesh.MeshParts)
{
// Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer.
Game.GraphicsDevice.SetVertexBuffers(
new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0),
new VertexBufferBinding(instanceVertexBuffer, 0, 1)
);
Game.GraphicsDevice.Indices = meshPart.IndexBuffer;
// Set up the instance rendering effect.
Effect effect = meshPart.Effect;
//effect.CurrentTechnique = effect.Techniques["HardwareInstancing"];
effect.Parameters["World"].SetValue(modelBones[mesh.ParentBone.Index]);
effect.Parameters["View"].SetValue(view);
effect.Parameters["Projection"].SetValue(projection);
effect.Parameters["Texture"].SetValue(texture);
// Draw all the instance copies in a single call.
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
Game.GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0,
meshPart.NumVertices, meshPart.StartIndex,
meshPart.PrimitiveCount, instances.Length);
}
}
}
}
// ### END FUNCTION DrawModelHardwareInstancing
The problem is the cube mesh you are using. The normals are averaged, but I guess you want them to be orthogonal to the faces of the cubes.
You will have to use a total of 24 vertices (4 for each side) instead of 8 vertices. Each corner will have 3 vertices with the same position but different normals, one for each adjacent face:
If the FBX exporter cannot be configured to correctly export the normals simply create your own cube mesh:
var vertices = new VertexPositionNormalTexture[24];
// Initialize the vertices, set position and texture coordinates
// ...
// Set normals
// front face
vertices[0].Normal = new Vector3(1, 0, 0);
vertices[1].Normal = new Vector3(1, 0, 0);
vertices[2].Normal = new Vector3(1, 0, 0);
vertices[3].Normal = new Vector3(1, 0, 0);
// back face
vertices[4].Normal = new Vector3(-1, 0, 0);
vertices[5].Normal = new Vector3(-1, 0, 0);
vertices[6].Normal = new Vector3(-1, 0, 0);
vertices[7].Normal = new Vector3(-1, 0, 0);
// ...
It looks like you've got improperly calculated / no normals.
Look at this example, specifically part 3.
A normal is a vector that describes the direction that light would reflect off that vertex/poly if shined orthogonally to it.
I like this picture to demonstrate The blue lines are the normal direction at each particular point on the curve.
In XNA, you can calculate the normal of a polygon with vertices vert1,vert2,and vert3 like so:
Vector3 dir = Vector3.Cross(vert2 - vert1, vert3 - vert1);
Vector3 norm = Vector3.Normalize(dir);
In a lot of cases this is done automatically by modelling software so the calculation is unnecessary. You probably do need to perform that calculation if you're creating your cubes in code though.

Resources