texts: OpenGL: missing GL_SPECULAR light on the texture

texts:
I'am missing specular lighting on the texture. I have #include <GL/glext.h> in the project, so basically I used glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SEPARATE_SPECULAR_COLOR_EXT); for specular effect. My init code:

glEnable(GL_DEPTH_TEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_CULL_FACE);
GLfloat AmbientLight[]   = {  0.3,  0.3,  0.3,  1.0 };
GLfloat DiffuseLight[]   = {  0.7,  0.7,  0.7,  1.0 };
GLfloat SpecularLight[]  = {  1.0,  1.0,  1.0,  1.0 };
GLfloat Shininess[]      = { 90.0 };
GLfloat Emission[]       = {  0.0,  0.0,  0.0,  1.0 };
GLfloat Global_Ambient[] = {  0.1,  0.1,  0.1,  1.0 };
GLfloat LightPosition[]  = { 7.0, 7.0, 7.0,  1.0 };

glLightModelfv(GL_LIGHT_MODEL_AMBIENT, Global_Ambient);
glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularLight);
glLightfv(GL_LIGHT0, GL_POSITION,LightPosition);

glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION,  0.05f );
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION,    0.03f );
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.002f);

glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, AmbientLight);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, DiffuseLight);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, SpecularLight);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, Shininess);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Emission);

glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);

My render code:

glClearColor( 0.117f, 0.117f, 0.117f, 1.0f );
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// load texture
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_LIGHTING);
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SEPARATE_SPECULAR_COLOR_EXT);
glColor4f(1.0, 1.0, 1.0, 0.2);
glDisable(GL_COLOR_MATERIAL);
// render geometry here
glFlush();

What is missing here?


texts: 2D Animation Smoothness - Delta time vs. Kinematics

texts:
I'm animating a sprite in 2D with key frames of rotation and xy-positions.

I've recently had a discussion with someone saying that when the device (happens to be an iPad using cocos2D) hits a performance bump due to whatever else the user may be doing, lag will arise and that the best way to fight it is to not use actual positions, but velocities, accelerations and torques with kinematics. His message is to evaluate the positions and rotations from these speeds at the current point in time.

I've never experienced a situation where I've heard of using kinematics to stem lag in 2D animations and am not sure of how effective it could be. Also, it seems to be overkill.

The application is not networked so it's all running on a local device. The desired effect is that the animation always plays as closely as it can to the target frame rate.

Wouldn't the technique suffer the same problems as just using the time since the last frame or a fixed time step since the kinematics would also require some time value to perform the calculation?

What techniques could you suggest to best achieve the desired effect?

EDIT 1

Thank you for your responses, they are very illuminating. I want to clarify my question before choosing an answer however, to make sure that this post really serves it's purpose.

I have a sprite of a ball, and a text file with 3 arrays worth of information (rotation,translations x, translations y) with each unit of information existing as a key frame to be stepped through (0 to 49 and back to 0 to replay it again). I have this playing by interpolating from the current key frame to the next, every n-units of time. The animation is visibly correct when compared to a video I was given of it, and it is smooth because of the interpolations between the key frames. This is the existing state of the project.

There are no physics simulated, only a static animation of a ball moving in a way an artist specifically designed.

Should I, instead of rotation in degrees and translations by positions in space, derive velocities, accelerations and torques to express this static animation as a function of time? As in, position now = foo(time now), where foo uses kinematics.


texts:
I am making an FPS, in Unity. I have a player with a gun, and I have a bullet prefab. I changed the mouse pointer to look like a crosshair, but I don't know how to place the bullet where the crosshair is aiming.

The player movement is on the x and z axis. I have done lots of research on the Internet, and couldn't find anything suitable; most of what I found, I could not understand enough to change it according to my needs.

How do I set up a bullet to fire towards the mouse pointer?


texts:
I'm basically bumming around using Unity's 2D creation tools, and I've managed to create a little platformer physics demo. There's a lot of work to be done, but I've got basic movement down, some sounds working, basic jumping physics, and whatnot.

One of the things that's on my list of things to tackle is the camera system.

I experimented with locking the camera to the player position; it's simple, but works. However, I'd like to attempt to develop a more complex camera system that would follow level constraints, but still allow for free vertical and horizontal movement. Currently, I have the camera only matching the player's movement on the X axis, which means that jumping doesn't affect the camera. However, the camera won't follow if you climb a tall ladder.

(Think of the viewport from the Megaman X SNES games; there are many vertical and horizontal segments, but the camera is smart enough to let the player character (X) jump or cling to walls at the edge of the viewport without moving, yet move when the player is in an open area. This is the type of camera I'd like to achieve.)

I'd like to know how this problem is commonly approached. I thought about creating a spline, perhaps, and having the camera follow the spline path while still tracking the player. This spline would be specific to each created level. However, I'm not sure if this is the correct solution (and I'm not sure how it would work in open areas). The other thing that might be possible could be to set bounds for the actual camera limits, and not allow the camera to move outside of that, but I feel as though that might be a brittle solution in tighter areas.

Could someone with experience point me to any resources, or suggest advice to go in the right direction? Thanks!

Edit: To make this more clear, I've included a link to Flame Mammoth's stage in Megaman X. Notice how, in the first part of the stage, X can dash along the ground, while the camera tracks his x-position; later, it tracks his y-position when he falls down a shaft. Further on, there's a large room where the camera tracks X's movement without any boundaries until he gets close to the top of the screen; the camera doesn't pan past those boundaries.

Of note, I found a solution here that helps with jumping; I believe that MMX uses a variant of this. However, notice that in the custom game at the bottom, the camera is allowed to pan "out of bounds" as it's not limited by the level.


texts: Implementing a score cheating prevention system in an offline game with an online score board: How to protect game fairness?

texts:
This is hopefully a very simple question. It isn't about loading assets (which is all I found while searching)

Basically I have a template, say Object_Monster that has stats, abilities, etc. But I don't want to abstract it and create Object_Monster_Witch, Object_Monster_Ghoul and so on.

I want to know the best way to store data for loading many "different" monsters for one monster class. But I don't want the data to be editable by players.

For example. Lets say a Ghoul has 50 max health, the name "Ghoul" and the Consume ability. I would want all those variables listed somewhere to then be loaded into Object_Monster so he can act as a Ghoul.

I hear people use XML for this sort of thing, but that is of course, edited on the fly. Should I be using just an in-code list of #defines? An array of monster data?


texts: How to smooth jagged pixel edges in Unity?

texts:
So I am reading an image from a png file into a 2D sprite. This sprite serves as a "province" in my game. Currently, I am getting this:

If you look closely, you will notice that you are seeing the square corners of each pixel, because I am mapping the image on a 1:1 ratio of pixels:world coordinates.

What I want is a slightly rounded corner in these places. Look at the 2-dimensional provinces in this example:

I have been googling around for algorithms, but most answers simply say "use a shader" and don't describe the techniques used to do this (until now I have not done much with shaders). If you would like to see my working code for the province system, it is posted on my answer to my own question here.


texts: Why is the framerate (fps) capped at 60?

texts:
ISSUE

I recently moved a project from my laptop to my desktop(machine info below). On my laptop the exact same code displays the fps(and ms/f) correctly. On my desktop it does not. What I mean by this is on the laptop it will display 300 fps(for example) where on my desktop it will show only up to 60. If I add 100 objects to the game on the laptop I'll see my frame rate drop accordingly; the same test on the desktop results in no change and the frames stay at 60. It takes a lot(~300) entities before I'll see a frame drop on the desktop, then it will descend. It seems as though its "theoretical" frames would be 400 or 500 but will never actually get to that and only do 60 until there's too much to handle at 60. This 60 frame cap is coming from no where.

I'm not doing any frame limiting myself.

It seems like something external is limiting my loop iterations on the desktop, but for the last couple days I've been scratching my head trying to figure out how to debug this.

SETUPS

Desktop:

Visual Studio Express 2012
Windows 7 Ultimate 64-bit

Laptop:

Visual Studio Express 2010
Windows 7 Ultimate 64-bit

The libraries(allegro, box2d) are the same versions on both setups.

CODE

Main Loop:

while(!abort) {
    frameTime = al_get_time();
    if (frameTime - lastTime >= 1.0) {
        lastFps = fps/(frameTime - lastTime);
        lastTime = frameTime;
        avgMspf = cumMspf/fps;
        cumMspf = 0.0;
        fps = 0;
    }

    /** DRAWING/UPDATE CODE **/

    fps++;
    cumMspf += al_get_time() - frameTime;
}

  Note: There is no blocking code in the loop at any point.

Where I'm at

My understanding of al_get_time() is that it can return different resolutions depending on the system. However the resolution is never worse than seconds, and the double is represented as [seconds].[finer-resolution] and seeing as I'm only checking for a whole second al_get_time() shouldn't be responsible.

My project settings and compiler options are the same. And I promise its the same code on both machines.

My googling really didn't help me much, and although technically it's not that big of a deal. I'd really like to figure this out or perhaps have it explained, whichever comes first. Even just an idea of how to go about figuring out possible causes, because I'm out of ideas.

Any help at all is greatly appreciated.

EDIT:

Thanks All. For any others that find this to disable vSync(windows only) in opengl:

First get "wglext.h". It's all over the web.

Then you can use a tool like GLee or just write your own quick extensions manager like:

bool WGLExtensionSupported(const char *extension_name) {
PFNWGLGETEXTENSIONSSTRINGEXTPROC _wglGetExtensionsStringEXT = NULL;

_wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT");

if (strstr(_wglGetExtensionsStringEXT(), extension_name) == NULL) {
    return false;
}

return true;
}

and then create and setup your function pointers:

PFNWGLSWAPINTERVALEXTPROC       wglSwapIntervalEXT = NULL;
PFNWGLGETSWAPINTERVALEXTPROC    wglGetSwapIntervalEXT = NULL;

if (WGLExtensionSupported("WGL_EXT_swap_control"))
{
    // Extension is supported, init pointers.
    wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");

    // this is another function from WGL_EXT_swap_control extension
    wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) wglGetProcAddress("wglGetSwapIntervalEXT");
}

Then just call wglSwapIntervalEXT(0) to disable vSync and 1 to enable vSync. I found the reason this is windows only is that openGl actually doesn't deal with anything other than rendering it leaves the rest up to the OS and Hardware.

Thanks everyone saved me a lot of time!


texts: How do I implement a Camera in the PushButton Game Engine?

texts:
I am playing around a bit with the PushButton Engine for game development in Flash and have come across a need for a Camera like the Camera that follows Mario in Mario Games. Flashpunk has a nice implementation of it.

Does PushButton have it out of the Box?(I searched for it and didn't find, hence the question here). If not then if any of you have written a component for the same, or can guide in the direction, any help would be much appreciated.


texts: Touch Coordinate in onManageUpdate method

texts:
I want to get touch coordinate in onManageUpdate() method. So how to perform that one?

Because onSceneTouchEvent method simulation is some what slow so I could not able to get each coordinate in move event. So to achieve each coordinate in move event I want this functionality.

So someone please help me in this.


texts: How to revert to MonoDevelop's old "ctrl-tab" behavior?

texts:
I believe MonoDevelop (bundled with Unity3D) has changed its ctrl-tab and ctrl-shift-tab behavior and I would like to get back to the old behavior, as the new way frustrates my workflow.

Ctrl-tab (and ctrl-shift-tab) previously (and ought to) go to the "last viewed tab", in a similar way to how alt-tab works on Windows. Unfortunately there seems to have been a change and now it goes to the "tab on the left of the current one".

An example of why this is frustrating: quickly looking at a class definition, you hit F12 to load the definition (perhaps in a new tab), and then you want to go back to the code you were working on. Previously you could hit ctrl-tab and you'd be back there. Now you can't do that and you have to actually remember what you were doing, which isn't good for my workflow (read: ailing memory).

I'm not sure when the change happened, or if it's a setting somewhere (I can't find it). I'm running Unity 5.1.2p2 and its bundled MonoDev 4.0.1. Noticed it after a clean install of Windows 10.

How can I fix this to revert to the old behaviour, or is there some other method to jump back to the last viewed tab?

It seems pedantic but it has a major impact on my productivity.


texts: Best way to develop a level from Top down image using 3dmax

texts: I have to create a game level from a top down view of an area. I used a plane converted to an editable poly to do the job. I used edges to create the top view of roads, walkways and parks so that i can extrude/edit them later. My problem is the curves in the road look blocky I tried appying mesh smooth modifier on the final model but that interfered with material mapping. Again i tried it on the plane without the extrusions and still the modifier does not work(The roads loose their shape). I know one way to solve the problem is to add more vertices on the curve and transform their location to create a more natural curve but i have a lot of curves so before doing it manually i need to know if there is a tool that refines the curves. Also i need to know if there is a better or proper way of doing the task.


texts: How do you make a object that always follow another object?

texts:
I'm trying to make a game object follow another game object and switch to another when a button is pressed. But right now it just seems to change the position when the button is pressed but it doesn't follow the object. How can I make it follow the other object?

public Transform PosObjOne;

public Transform PosObjTwo;

public Transform PosObjThree;

void Update () {
    if (Input.GetButtonDown("UseVr"))
    {
        PosObjThree.position = PosObjTwo.position;
    }

    if (Input.GetButtonDown("NoVr"))
    {
        PosObjThree.position = (PosObjOne.position);
    }
}


texts: Unity: Saving scene after using script to change object positions

texts:
I have a c# script which makes some edits to object positions in the editor. It does this by reading some values from a csv file and then changing the value of transform.position for each gameobject. When I run the script all the objects appear where I want them to be in the editor. However, the editor doesn't seem to recognise any change and when I save and reload the scene the objects have reverted to their previous positions. Any ideas?

Code:

GameObject go = GameObject.Find(values[1]);
Undo.RecordObject(go,"setting at rest");
// Do transforms
float x = float.Parse(p_values[0]);
float y = float.Parse(p_values[1]);
float z = float.Parse(p_values[2]);
Vector3 p = new Vector3(x,y,z);

go.transform.position = p;

Aha I think I see my error, Undo.RecordObject want the specific object that is changing rather than the gameobject. I've edited the code to Undo.RecordObject(go.transform,"setting at rest"); and it now seems to work


texts: Impact of variable-length loops on GPU shaders

texts:
Its popular to render procedural content inside the GPU e.g. in the demoscene (drawing a single quad to fill the screen and letting the GPU compute the pixels).

Ray marching is popular:

This means the GPU is executing some unknown number of loop iterations per pixel (although you can have an upper bound like maxIterations).

How does having a variable-length loop affect shader performance?

Imagine the simple ray-marching psuedocode:

t = 0.f;
while(t < maxDist) {
    p = rayStart + rayDir * t;
    d = DistanceFunc(p);
    t += d;
    if(d < epsilon) {
       ... emit p
       return;
    }
}

How are the various mainstream GPU families (Nvidia, ATI, PowerVR, Mali, Intel, etc) affected?  Vertex shaders, but particularly fragment shaders?

How can it be optimised?


texts: 2D Real-Time shadows on level on a level made from a Dynamic Bitmap

texts:
The Bitmap has transparency, and only non-transparent pixels are solid and used for hit detection for the physics engine and gameplay.

I have seen some versions done with convex hulls, but for multiple reasons I am not using convex hulls to build the levels in my game.

How can I implement 2d shadows on a level made out of a Dynamic Bitmap?

The answer jpaver posted is good, but I am sure there are some other ways to do this. Does anyone else have any more information on this question?


texts: Water4Advance far view seems stale and plain

texts:
Hi How can I remove far clipping in Water4Advance so that it matches near view like following img?

Currently far view water seems plaine with no wave n bumps at all.


texts:
In my Ogre 3d scene I have an empty box, and within that there are three small cubes. The camera is also within the box, facing the three small cubes. The user can move and rotate the camera with the mouse.

There is only one (spot) light source, attached to the same node and facing the same direction as the camera. The idea is that the light should always spot the same direction as the camera, like a flash light (with a narrow light cone).

The problem now is that the light emitted by the spot light used in this scene is not reflected by the sides of the empty box correctly. When I face the camera perpendicular to a side of the box, then no light is reflected at all. Only when I move/rotate the camera so that it spots the box "walls" from a specific angle some light is reflected. The problem only occurs with the box sides, the small cubes within the box are reflecting the light correctly.

In this first screenshot you can see what happens when I look to the edge/corner of the box. You can see a wooden texture on the box sides, and those three cubes in the box. The blue-ish box in the middle is exactly on the border of the light cone, so that only the left side is within the cone and reflecting the light.

That seems like the correct behaviour. Now when I move the camera so that I looks exactly top-down to the same cube within the box, then only that cube is reflecting the light, but not the side of the box. It then looks like as the empty box would not be there at all, as you can see on the second screenshot. (Note also a second small cube on the top of the screenshot, which is again exactly on the border of the light cone.)

I am pretty sure the texture/material is not the problem. Because when I use the same blue-ish material for the box sides as I use for the small cube, then the cube is still correctly reflecting the light, whereas the box side is again not reflecting the light at all.

Any ideas what I am doing wrong here?
I am completely out of ideas here :(


texts: How should chat be transmitted and stored in an MMO?

texts:
Players in MMO games can usually send messages over different channels (private, public, guilds, et cetera).

How would I transmit and store this data so as to prevent outside users from being able to access somebody's private chat messages? Should I store the data in a temporary game log, or a database?


texts: How to rotate a parent object while rotating a child object to a certain angle using coroutines

texts:
I have a semicircle like game object which I made by putting two arcs in an empty game object (SCircle) and rotating the 15° (for left arc) and -15° (for right arc) as seen below.

SCircle has an Orientation enum  with two valuesLeft (rotates SCircle to 45°) and Right (rotates SCircle to -45°) as seen in the image below.

I use the following coroutine to move SCircle between orientations.

IEnumerator RotateLeftOrRight(Vector3 byAngles, float inTime)
{
    Quaternion fromAngle = gameObject.transform.rotation ;
    Quaternion toAngle = Quaternion.Euler (transform.eulerAngles);

    if (circOrientation == Orientation.Left) {
        toAngle = Quaternion.Euler (gameObject.transform.eulerAngles - byAngles);
        circOrientation = Orientation.Right;

    }
    else if (circOrientation == Orientation.Right) {

        toAngle = Quaternion.Euler (gameObject.transform.eulerAngles + byAngles);
        circOrientation = Orientation.Left;
    }

    for(float t = 0f ; t <= 1f ; t += Time.deltaTime/inTime)
    {
        gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t) ;
        yield return null ;

        gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, 1);
    }

}

I also used a very similar coroutine to move the individual arcs by 30° (in opposite directions) from say, Orientation Left, as seen below:

Since SCircle Coroutine is activated by a mouse click, I have the case where the individual arcs coroutine is run and before it is complete the parent SCircle coroutine is also run. In this case the arcs end up moving from Left to A, which is not the behavior I need. I would want the behavior of them ending up at B when moving from the Left. Likewise, from B, when the SCircle coroutine is run while the arcs coroutine is in progress the orientation will return to the Left.

Please note that the blue arrow represents the movement of the left Arc, the red represents the right Arc and the black represents movement of SCircle - the parent object.

How can I achieve the behavior from Left to B and from B back to Left?


texts: What causes the iOS OpenGLES driver to allocate extra memory?

texts:
I'm trying to optimize the memory usage of our iOS game and I'm puzzled about when/why the iOS GLES driver allocates extra memory at runtime... When I run our game through Instruments with the OpenGL ES Driver instrument the gartUsedBytes value can fluctuate quite wildly. We preload all our textures and build the buffer objects up front, so it's not the game engine requesting extra memory from GL.

Currently we are manually requesting around 50MB of GL memory, yet the gartUsedBytes value sits at around 90MB most of the time, peaking at 125MB from time to time. It seems to be linked to what you are rendering that frame - our PVS only submits VBO's for visible meshes.

Can anyone shed some light on what the driver is doing in the background ? Like I said earlier, all our game engine allocations are done on level load, so in theory there shouldn't be any fluctuation on GL memory usage while the level is running.

Thanks.


texts: How to display consistent background image

texts:
Drawing a large background is relatively slow in PyGame.
In order to avoid drawing BG every frame, you could draw it once, then do nothing.

However, if something is overdrawn onto the surface and keeps moving, you will need to redraw the background in order to "erase" the color pixels left by moving object; otherwise, you will have "traces" of the moving object.

I have a moving object in my PyGame. However, I do not want to "clear the color buffer" by redrawing the background image. Redrawing the background image every frame is slow.

My solution :

I will "clear" only required portions (where the "traces" of moving object are left)  of the "buffer" by redrawing portions of background.

Is there any other better way to have a consistent background?


texts: Downloading image to apply as a Texture fails

texts:
In my app I need to download some images and apply them as Textures.

If I use following code to get image from my local pc hard disk, it works.

But it does not work if I use a url like (http://www.something.com/image.jpg). In that case, the texture appears as the image below.

More specifically:

The image I'm downloading is not the one I've attached.
The image/url exists and is accessible
The image is a JPG
Loading the same image stored on my local pc works ( file:// instead of http:// )

Texture2D tex;
tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
if (url.Substring(0, 4).ToLower() != "http")
    url = "file://" + url;
using (WWW www = new WWW(url))
{
    www.LoadImageIntoTexture(tex);

    while (!www.isDone) { }
    if (www.error==null)
    {

        MyObject.GetComponent<Renderer>().material.mainTexture = (Texture)tex;
    }

}


texts: What are some of the more commonly used projectile rendering techniques?

texts:
couldn't find a duplicate question (bit surprising to me) but anywho I'm starting to get near implementing the rendering of projectiles for my game.

My question is what are some good techniques for efficiently rendering projectiles? I would like emphasis on techniques that leave room for the projectiles to be "rich" and dynamic (Cool to look at!)

I'm also using DX11 for my rendering engine so bleeding edge techniques that can make use of that would be much appreciated too.

Thanks!


texts:
This may not be an appropriate question for gamedev.stackexchange.com.

I'd like to make a basic Breakout game with Unity.
I'd also like to sell it on the Mac App Store, iOS App Store, Google's Play Store, Windows 8 Store etc.

I'm not sure however if that will cause trouble with Copyright.
I asked Google but I didn't find any helpful results.

Can I use the game-concept without buying a license?

I know that there are plenty of games with the same concept on various platforms, I just want to be certain.


texts:
I am making a game in SFML, and whilst I was making an AI moving system I was wondering which would be better, If I was to instance update all my entities at once, or individually update them via a function in each of the entity class instances.

I know that instance rendering is much faster but was wondering if this would even be needed for updating the logic of the game, afterall I'm not making a giant physics simulation.

So, I am wondering what would the effect be if I updated the game logic for each entity individually or did it via instancing. And if there is an impact is it really worth it for a game like mine where there isn't too much complexity.


texts: Is using a dedicated thread just for sending gpu commands a good idea?

texts:
The most basic game loop is like this :

while(1)
{
   update();
   draw();
   swapbuffers();
}

This is very simple but have a problem : some drawing commands can be blocking and cpu will wait while he could do other things (like processing next update() call).

Another possible solution i have in mind would be to use two threads :

one for updating and preparing commands to be sent to gpu, and one for sending these commands to the gpu :

//first thread
while(1)
{
   update();
   render(); // use gamestate to generate all needed triangles and commands for gpu
             // put them in a buffer, no command is send to gpu
             // two buffers will be used, see below
   pulse(); //signal the other thread data is ready
}

//second thread
while(1)
{
   wait();              // wait for second thread for data to come
   send_data_togpu();   // send prepared commands from buffer to graphic card
   swapbuffers();
}

also : two buffers would be used, so one buffer could be filled with gpu commands while the other would be processed by gpu.

Do you thing such a solution would be effective ? What would be advantages and disadvantages of such a solution (especially against a simpler solution (eg : single threaded with triple buffering enabled) ?

EDIT :
I have taken a real example to show a situation where there would be an advantage :

Let's say i have a scene which consist of rendering same entity a lot of times (like in a RTS) :

in this example :

updating world take 100 ms (because there is lot of entities)
sending commands to gpu almost nothing (only calls to gldrawelements for the same entity, vertex buffers only sent once) (almost 1ms)
scene rendering by gpu is also heavy, take 100 ms

total = ~200 ms (or 5 fps)

I dont think gpu could be draw something during update procedure because gpu doesnt have any idea when scene start (and cant assume glclear = beginning of scene rendering)

now lets say the system is using two independant threads :

update take 100ms
sending cmds take 1ms
next update can already start no need to wait for gpu
scene rendering take 100ms

total = ~100 ms (actually a little more than this because of synchronisation)


texts: LIBGDX Perspective Camera in an Isometric view?

texts: how can I set a PerspectiveCamera to view the game in an isometric view? What kind of angle would I use, and how would I actually translate this into the code? Math isn't my forte, so I can't really understand the maths on the wikipedia article here. It mentions to points A and B, but I'm not sure what those points would be.


texts: How to prevent automation-type cheating?

texts:
Lets say I'm making an incremental game, (e.g. cookie-clicker-like). The premise of the game is simple: players send inputs that advance their game state. Players convert their own real-life time into progress in the game.

Obviously, players can cheat on the client-side, so to prevent this - the entire game logic happens on the server, and the client's only role is to render an interface that lets the players send their inputs to the server over the network. Thus, players can't take any actions that aren't allowed by the game's rules, because each action is validated on the server.

However, this still brings up a problem: what about this type of cheating:

Instead of playing the game manually, a player just writes a script that plays the game for them. They leave their PC running 24/7, and make progress in the game, all within the game's rules, but without using their own real-life time to play.

Obviously, this gives an edge over "legit" players that only play using the game's intended interface for committing actions.

Is there anything I can do to prevent this type of cheating, or is this a lost cause with no solution?

For the sake of this discussion, assume that the player that wants to cheat is able to easily reverse engineer the clientside code. For example lets say it's an HTML5 game with JS code, and that the cheater is smart enough to read minified code (which is not a far stretch at all). This means they can basically copy the code to their own machine, set up a server (with the JS example, setting up a Node.js server takes about 2 minutes), add a bit of their own code for the automation, and make their server send requests to my server with spoofed headers in a way that it pretends to be a regular user agent.

[Edit] in response to questions in the answers:
The game has no player interaction, but there's an online scoreboard, and higher-ranking players get rewards; in other words, cheating is not isolated to the cheater's local machine, and cheating can ruin the experience for other players.


texts: How do I flatten terrain under a game object?

texts:
I've got a script that makes a terrain object and paints it with textures, but I'm having an issue.  When I attempt to place game objects (such as the simple water object that unity provides), I use a Raycast to determine the correct height to place the game object, but that just ensures that it is correctly placed at that particular point.

How would I go about flattening the terrain under the game object so that it doesn't go into the terrain or hang out into thin air in the case of hills?


texts: In UE4's Blueprints, how do I activate something when the player looks at it?

texts: I want to make an object that activates when the player presses a button, then looks at it. How can I do this using Blueprints Visual Scripting?


texts: What is wrong with my gravity calculation?

texts:
Im trying to create a method to calculate the fall time for an object using real formulas. Well I came up with this:

    public static double calculate_fall_time(float height) {
        final float GRAVITY = 9.81f;
        float h = (1/2)*GRAVITY*2;
        float h2 = GRAVITY/GRAVITY;
        double t = Math.sqrt(((2*h2)/GRAVITY));

        return t;
    }

Well I used to this website to compare the results but it wasn't the same. If I have 370 at the input then my program shows 0.4515 but the website is showing around 8,6 seconds.

Does anybody know how I can fix this problem? Thanks in advance :D

NOTE: I know that arcade physics are much more fun but my goal is to create a rather realistic game. Thanks for reading.


texts:
I love the humble bundle.  They are getting more and more generous, now including Pack #3 with Pack #4.

I am so confused.  Will they last?  Are they doing ok?  They're putting so much out there, and if you donate less than $1, you get this image :

And that's it!

Is this really working?


texts:
How can I create a wrap around unlimited 3D terrain:
To make it clear:
If I step out of terrain in (1) or (A) I want to get to (2) resp. (B)

        |B
        V
     +----------+
2 -->|          |--> 1
     |          |
     |          |
     +----------+
        |A
        V

I do not know how to wrap around the terrain and all the items which are on the terrain(NPCs etc) I thought of portals, but then I have problems on the corners of the terrain.
In 2D it is quite simple(even trivial), but on 3D I cannot find a solution..
Any advice or tutorial ailable?


texts: When should I use instancing versus a constant buffer?

texts:
I've heard something about instancing and understood it's useful for drawing the same object many times with slight changes. It's faster because you call the draw function once per frame and update the buffer (in this case the instance buffer) once per frame too while with constant buffers, for example, if you need a world matrix you have to update your constant buffer once per object.

But if I have only one object, would instancing be faster (or at least as fast as) using a constant buffer? With instancing, you have to call only an update buffer function (for the vertex-instance buffer) while with CB you need two calls: one for the vertex buffer and one for the constant buffer.

Another question about instancing:

Since I have to update the instance buffer once per frame, I need to create it with DYNAMIC_USAGE and with a byte width representing the maximum number of objects I can draw with one call. For example, if I want to pass a matrix, I need insBufferdesc.bwitdh= sizeof(matrixtype)*maxNumObjs. Is this right? Given that maxNumObjs is 20 and I want to render only 10 objs, I've should just update the first 10 matrices of the buffer and call drawInstanced(..., 10). Will I get some error if I don't use all of the buffer?


texts: How do I reverse the playback of an animation (instead of restarting it)?

texts:
I have created a sprite sheet of which consists of six frames of a character whose legs move each frame. Now I have written code so that the animation is running successfully from frame one to frame six, however I am trying to reverse this so then instead of looping back to frame one after the last frame, the animation moves backwards from frame six to frame one and then repeats in a continuous loop.

I handle the animation currently like this:

void SpriteGame::Update(int tickTotal, int tickDelta)
{
    if ( tickTotal >= this->playerLastFrameChange + 4)
    {
        //Four ticks have elapsed since the last frame change
        this->playerFrame = this->playerFrame + 1;
        this->playerLastFrameChange = tickTotal;  //We've just changed the frame

        if (this->playerFrame >= this->playerSheetLength)
        {
            this->playerFrame = playerLastFrameChange + 4;
        }

        //Frame has changed so change the source rectangle
        this->playerSourceRect->left = this->playerFrame * 64;
        this->playerSourceRect->top = 0;
        this->playerSourceRect->right = (this->playerFrame + 1) * 64;
        this->playerSourceRect->bottom = 64;
    }
}

How can I accomplish this using Direct3D 11?


texts: How can I trigger to start timeline using distance and not OnTriggerEnter/Exit?

texts:
using UnityEngine;
using UnityEngine.Playables;

public class GenericTrigger : MonoBehaviour
{
    public PlayableDirector timeline;

    // Use this for initialization
    void Start()
    {
        timeline = GetComponent<PlayableDirector>();
    }

    void OnTriggerExit(Collider c)
    {
        if (c.gameObject.tag == "Player")
        {
            timeline.Stop();
        }
    }

    void OnTriggerEnter(Collider c)
    {
        if (c.gameObject.tag == "Player")
        {
            timeline.Play();
        }
    }
}

The idea is to create some kind of cut scene.
Once the player (First person, in the screenshot i'm just showing the door on the left where the player will come from and the soldiers ) exit the door on the left and is in a specific distance from the soldier the first soldier the closet one will start moving to the player. Later I will make that it will change to close up view on the soldier with some text conversion. That's the main goal.

But the script the original script by the unity tutorial is using triggers.
I'm not sure if I should using this way or using somehow by calculating the distance between the player and the soldier to start the timeline ? And how to do it.

After the soldier is moving/walking to the player at some point I will make it to change to a close up view on the soldier with blurry background something like this:

But first how should I approach to the triggering part ?


texts: Do I need licensing to use real city names in my game?

texts: I want to allow people to go to real places (Seattle Washington, Portland, Maine, etc.) in my game. Will I need licensing to make those places and use their names?


texts: Is * calling *= (or *= calling *) slower than writing seperate functions (for math library)?

texts:
I have some vector classes where the arithmetic functions looks like this:

template<typename T, typename U>
auto operator*(const Vector3<T>& lhs, const Vector3<U>& rhs)
{
    return Vector3<decltype(lhs.x*rhs.x)>(
        lhs.x + rhs.x,
        lhs.y + rhs.y,
        lhs.z + rhs.z
        );
}

template<typename T, typename U>
Vector3<T>& operator*=(Vector3<T>& lhs, const Vector3<U>& rhs)
{
    lhs.x *= rhs.x;
    lhs.y *= rhs.y;
    lhs.z *= rhs.z;

    return lhs;
}

I want to do a bit of cleanup to remove duplicated code. Basically, I want to convert all the operator* functions to call operator*= functions like this:

template<typename T, typename U>
auto operator*(const Vector3<T>& lhs, const Vector3<U>& rhs)
{
    Vector3<decltype(lhs.x*rhs.x)> result = lhs;
    result *= rhs;
    return result;
}

But I'm concerned as to whether it will incur any additional overhead from the extra function call.

Is it a good idea? Bad idea?


texts: Working around the current sad state of mobile GPU drivers

texts:
I'm working on a OpenGL ES3 app for Android: for various reasons, I decided to roll my own mini-OpenGL rendering engine. So far so good.

Problem is, the GPU drivers in the mobile industry are such sad things, that dire bugs keep appearing with the most innocent actions.

For example: yesterday I added a point to my scene (you know: the kind with 3 coordinates, plus a mat4 for the projection matrix) and I got the following results:

everything fine on a Samsung S4
black screen with ANR on my Nexus 5
hard freeze and reboot on my Nexus 7 (way to go, Qualcomm!)

I admit I use a number of not so common stuff in my rendering engine (the tougher probably being MRT), but we are still talking about features in the OpenGL ES 3 specification.

So the question is: how do you deal with this state of affair? Are there techniques that will minimise the risk of incompatibilities? Does the OpenGL ES 3 (and 2 since we are at it...) specification contains features better not using?

Mind that this is not the first time I stumble on problems like this (earlier during development I had a bug triggered by the GL_TEXTURE_EXTERNAL_OES OpenGL ES2 extension that actually forced me to do a pre-rendering pass, just to avoid getting a purple screen...), and this is turning the whole development into a quite anxiety-provoking experience.

Thank you for any advice!


texts: How do you make a shape slide on a JFrame?

texts:
I have some simple code that draws a dot in one of 8 places on a screen. There is a higher chance the dot will appear in some locations more than others. The code works and all, but it feels kind of weird that the dot is teleporting from one location to the other. I would like for the dots to slide in a circle that I have drawn, can someone please help me out?

Here is my code:

  package com.company;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Main extends JPanel {

    private static JFrame frame = new JFrame();
    private static int random = 1;

    public static void main(String[] args) {

        //Time -= 5 every time used
        Runnable number = () -> random = (int) (Math.random() * 100) + 1;
        ScheduledExecutorService executor1 = Executors.newScheduledThreadPool(1);
        executor1.scheduleWithFixedDelay(number, 0, 1, TimeUnit.SECONDS);
        frame.getContentPane().add(new Main());
        frame.setSize(2000, 1080);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.WHITE);
        frame.setVisible(true);
        frame.setResizable(true);
    }

    public void paint(Graphics g2) {
        Graphics2D g = (Graphics2D) g2;
        if (random > 0 && random <= 15) {
            g.fillOval(920, 3, 100, 100);

        } else if (random > 15 && random <= 20) {
            g.fillOval(920, 797, 100, 100);

        } else if (random > 20 && random <= 35) {
            g.fillOval(523, 400, 100, 100);

        } else if (random > 35 && random <= 50) {
            g.fillOval(1317, 400, 100, 100);

        } else if (random > 50 && random <= 65) {
            g.fillOval(620, 143, 100, 100);

        } else if (random > 65 && random <= 80) {
            g.fillOval(1220, 143, 100, 100);

        } else if (random > 80 && random <= 90) {
            g.fillOval(620, 657, 100, 100);

        } else if (random > 90 && random <= 100) {
            g.fillOval(1220, 657, 100, 100);
        }
        g.drawOval(570, 50, 800, 800);
        frame.repaint();
    }
}


texts: Errors happen when using World.destroyBody( Body body )

texts:
on Android application using libgdx, when I use World.destroyBody( Body body ) method, once in a while the application suddenly shuts down.

Is there some setting I need to do with body collision or Box2DDebugRenderer before I destroy bodies?

Below is the source I use for destroying bodies.

private void deleteUnusedObject( ) {
    for( Iterator<Body> iter = mWorld.getBodies() ; iter.hasNext() ; ){
        Body body = iter.next( ) ;
        if( body.getUserData( ) != null ) {
            Box2DUserData data = (Box2DUserData) body.getUserData( ) ;
            if( ! data.getActFlag() ) {
                if( body != null ) {
                    mWorld.destroyBody( body ) ;
                }
            }
        }
    }
}

Thanks


texts: What's wrong with using physics engine in 2d platformer?

texts:
I started making my simple 2D runner game with a splash of physics (particularly, rope physics). It's in Love2d, project is targeting mobile platforms. Development goes fine, though I meant to ask one thing.  Referencing this page: https://love2d.org/wiki/love.physics

The message at the top warns against using the physics engine for a platform game, and has an anology to heavy-lifting, but no good explanation as to what might go wrong, what exactly is so hard about it and why should I stay away from it.  Because so far I have my basic idea implemented and no bad experiences here. As to good ones, I was able to abstract all the collision handling and let physics engine just do it for me.

Given that using the physics engine for my platformer seemed to work well in my initial test, why do many people consider it a bad idea? I mentioned some upsides but what are the downsides?


texts:
I have made sudoku type game. I am about to complete my game in 2d. At present, my game run smoothly on higher configuration devices such as Sony Experia Sola, Samsung Note 2 and Google Nexus.

But it creates screen flickering problem in my HCL ME tablet. I don't what is problem going on. I notice that when I load prefabs then it start flickering problem. If I don't create any prefab then it don't flicker at all.

At present my development game resolution is 2048x1536. So friends I need support from your side. If you want any more detail then I will provide any time.


texts: How do I fix this Minecraft type game bug?

texts:
I'm making a building game similar to minecraft, except you can place other types of objects as well.  I am right now building the functionality of placing cubes.  I'm using unity.  here's my code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    Camera cam;
    [SerializeField] GameObject brick;
    float pointX;
    float pointY;
    float pointZ;

// Start is called before the first frame update
void Start()
{
    cam = FindObjectOfType<Camera>();
}

// Update is called once per frame
void Update()
{
    Ray ray = cam.ScreenPointToRay(Input.mousePosition);
    RaycastHit hitInfo;

    if(Physics.Raycast(ray, out hitInfo))
    {
        if(Input.GetMouseButtonDown(0))
        {
            pointX = hitInfo.point.x;
            int roundedX = Mathf.RoundToInt(pointX);
            pointY = hitInfo.point.y;
            int roundedY = Mathf.RoundToInt(pointY);
            pointZ = hitInfo.point.z;
            int roundedZ = Mathf.RoundToInt(pointZ);
            Vector3 clickedPlace = new Vector3(roundedX, roundedY, roundedZ);

            Instantiate(brick, clickedPlace, transform.rotation);
        }

    }
}
}

the brick variable is assigned to a prefab which s 1 unit by 1 unit.  this code works when placing the brick on the ground or on top of another block, but it only has a 50% chance of working when clicking on one side of the brick like you can do on minecraft.  Sometimes the block will be placed right on top of another block, and sometimes it will be placed above the block and in front of it.  does anyone know a way to fix this?  I tried making the collider on the block bigger, but it didn't work.


texts:
Okay I have the following code that works correctly. It loads a vertex array, a normal array and a vertex index array then draws them with some simple light shading.

To load the buffers:

//Load Buffers
//vertices
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(verts), &verts[0], GL_STATIC_DRAW); //verts is std::vector<float>
//normals
glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(normals), &normals[0], GL_STATIC_DRAW); //normals is std::vector<float>
//indices
glGenBuffers(1, &elementbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLushort), &indices[0] , GL_STATIC_DRAW);
//indices is std::vector<unsigned short> and in this working example only
//contains indices into the vertex array (I will add interleaved normal indices)

To draw the buffers:

//Draw Object
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_NORMAL_ARRAY );

//vertices
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);

//Indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);

//Normals
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glNormalPointer(GL_FLOAT, 0, (void*)0 );

//Draw the mesh
glDrawElements( GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, (void*)0);

//Clean up
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);

In this code, normals are not indexed. I would like to change it so that the normals are based on the the index in indices[] (same as vertices are now). indices[] is interleaved (not in the above code) as such: {vertex index,normal index,vertex index,normal index...}.

I've been trying to get this to work for some time without success and every example I've found online seems to use a different approach to VBOs making it very difficult to combine multiple examples into one that does what I need.

Help would be greatly appreciated. And if I'm doing anything in a less than ideal way, I'm open to suggestions.


texts:
If i want to use Physics in Unity2D what should be the most efficient way to move the object without interfering physics?

 1. Transform.position
 2. Rigidbody.Velocity
 3. Rigidbody.addForce
 4. Transform.translate
 5. Rigidbody.movePosition

Seems like there are a lot of ways and each way has a special purpose for when it should be used and when not. I just don't know that.


texts: Pathfinding and collision avoidance on mobile

texts:
Currently I'm developing a Diablo like game for mobile platform(iphone5+).

A simple A* search will find the path, but collision avoidance still needs to be taken into consideration.

There will be about 50 monsters active at the same time, so performance is very important.

I found some methods that might work.

NavMesh + RVO

The recast/detour library works well on the pathfinding part, but its crowd simulation quickly reach the limit(more than 5ms for 30 agents).

Another library RVO2 seems fine(less than 2ms for 50 agents), but the library has some license issues.
Flow Fields + Physics Engine

Many RTS games use this method, but it seems that a physics engine is required to resolve  collisions. If many agents don't share a common goal, this method might cost more than traditional A* pathfinding.
Steering Behaviors + Physics Engine

Steering Behaviors includes many concepts, I think simple avoidance behavior might work(just turn left/right if there is something in front) , but the method still requires a physics engine to work together.

I'm still not sure which one to use, maybe there exists other pathfinding and collision avoidance methods.

P.S. Halo:Spartan Strike uses Havok AI(based on RVO?), but I didn't see many enemies in that game,
so I wonder whether the first method(NavMesh + RVO) will works well on mobile platform.


texts: How can I take ingame images and videos?

texts:
I’m using MonoGame and Visual Studio Community on my Mac to develop a game for iOS. I want to take ingame images and videos of the gameplay while the game is running on an iPhone/iPad. Afterwards, I want to use these images and videos for promotional reasons on my website or on facebook.

Is it necessary to install third party software or can I take images and videos in Visual Studio Community without installing additional software?


texts: How to create "border" around tilemap in Unity

texts:
I'm setting up a 2D arena game, and I'm trying to implement an ability for tilemaps to be highlighted (on hover).  I've already managed to get a Vector3 of the hovered tile using rays and WorldToCell, but I don't know how to actually "highlight" the tilemap by creating a border around it.  Is this possible or am I going to need some other sprite that has a highlighted version of the tile?  Here's my layout now:

I need it to look something like this:


texts: How can I reduce the sharpness of my generated terrain?

texts:
I am trying to generate a random low poly terrain for a 3D demo. I am using Perlin noise to generate the heights and then generate the 3D mesh, but the terrain generated is too sharp and unrealistic. It ends up looking like this:

But I'd like it to look more like this:

How can I smooth out my terrain so it looks more like the second image?


texts:
In my class, I extend Sprite class. I override one of the method collideWith(). But my problem was that when current sprite collide with other sprite it does not call the call back method collideWith(). Here is my implementation.

@Override
public boolean collidesWith(IShape pOtherShape) {
    System.out.println("collide with called");
    return true;
}

Any member please help me.


texts: blender imported sphere with mesh collider not collided

texts:
here is the scene

i imported a sphere (the blue sphere) from blender (with a hole at back), i added a mesh collider on it but it has no effect, and there is an error message
Cooking::cookConvexMesh: user-provided hull must have less than 256 vertices!.

any ideas?

(update the collider work fine after i retry and retry, but the error message still stay)


texts: How to render an animated gif to the screen using SDL2?

texts:
So, I have an animated gif that is 5 frames (not the same as what is seen in this tutorial). Upon opening, my gif is already animating, unlike the png in the above tutorial.
How can I render it to the screen using SDL2?

The code I have now only renders the gif when I close out the window, and even then, it is only for a split second and I can only see one frame. How can I improve my code?

This is the code that implements the game's main loop:

#include "game.h"

int main( int argc, char* argv[])
{
    init();

    SDL_Texture* texture = IMG_LoadTexture(renderer, "male_base-test-anim.gif");
    SDL_Rect base;
    base.x = 0;
    base.y = 0;
    base.w = 948;
    base.h = 335;

    bool quit = false;

    SDL_Event e;

    while( !quit )
    {
        //Handle events on queue
        while( SDL_PollEvent( &e ) != 0 )
        {
            //User requests quit
            if( e.type == SDL_QUIT )
            {
                quit = true;
            }
        }
    }

    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, &base);
    SDL_RenderPresent(renderer);

    SDL_DestroyTexture(texture);
    texture = NULL;
    exit();
    return 0;
}


texts: Game asset "objects" consisting of several meshes vs continuous mesh

texts:
When building game objects in a 3D modeler like Blender I'm finding it's easier to get greater detail and still have fewer vertices if I separate certain elements. For example, I need to make cuts along certain edges to add appendages to that part of the mesh, which could potentially increase the poly count by a large number. If I simply add another mesh I don't need to cut new vertices into the mesh I'm extending. I'm talking about buildings and other structures that never move.

With static objects (that don't move, ever) I was thinking this wouldn't have any drawbacks... but someone may know otherwise. Will this have any visual artifacts or mess up lighting in an engine like Unity or UE4?

Thanks. Sorry if I didn't explain that clearly enough.


texts: Problems with Creating Snake's Clone on Java

texts:
I'm creating Snake's clone. My app have too classes: Snake.java and Board.java.

Right now I have three problems:

1) There are two constants - BOARDS_WIDTH, BOARDS_HEIGHT. They are meant to be dimensions for playground where snake moves and collects apples. It's dynamic and I can set them as I want. For example 640 x 480, 160 x 160 or whatever. Only thing I need to keep in my mind is that both numbers must divide with 16. Why? Because constant UNIT is set to 16 x 16 and, for example, when board's dimensions are set to 160 x 160, it means that there would be 10 x 10 units large playground (160 / 16 = 10). Problem: playground is always two pixels (not units) larger than it meant to be. Like if I have set dimensions to 160 x 160, actual dimensions will be 162 x 162! Here are screenshot...

If you measure this image... after pill (apple, if you like) there are two extra pixels.

2) Collisions. I think - it's because problem #1. You see, there are code lines...

if( x[0] < 0 || x[0] > BOARDS_WIDTH || y[0] < 0 || y[0] > BOARDS_HEIGHT ) {

    inGame = false;

}

They should prevent snake from going into walls. Actual result is that snake goes few units in the wall - then only the game stops... i want it to stop exactly when snake collide with the wall!

3) How to make snake start to move only when users clicks any of arrows? Right now it's like snake starts to move her body, but her head is stopped. After joints * DELAY snake's all joints are under her head! Ha, ha...


texts:
Implementing the suggestions from

this answered question, I am trying to move my player according to the animation. To do so, I am adding the transform.position property to the animation and then, considering only an horizontal left movement just for testing, I modified the curve like this:

By properly tuning the curve, I managed to move the character following the animation, however I am having two main problems:

1) As soon as I add the position property to the animation, the character does not move anymore, even if the animations are correctly showing up. My first thought is that my modifying the position I am actually forcing the gameObject to stay still in the position that I obtain from the curve. Another possibility may be a problem with my Move method:

private void Move()
{
    moveInput.Normalize();
    myRigidBody.MovePosition(myRigidBody.position + moveInput * moveSpeed * Time.deltaTime);
}

With MoveInput a 2d Vector storing the x and y value from my inputs and moveSpeed a float. Could it be that RigidBody2D.MovePosition is somewhat conflicting with the animation curve?

2) Even if the position changes during the animation, it goes back to the starting place once it ends, whereas I want the position to be updated with the final position assumed during the animation.

A solution using the animation interface would be great, but I don't mind one through scripting, I was looking for it initially but I am not understanding how to call a precise animation in a script and modify its properties.

Any hint would be much appreciated, cheers!

Update: I managed to make two simple functions to be called from the animation event that take a float as input to move the player either horizontally or vertically:

public class Animation_Tuning : MonoBehaviour
{
    private Rigidbody2D myRigidBody;

    void Start()
    {
        myRigidBody = GetComponent<Rigidbody2D>();
    }
    public IEnumerator Animation_MoveHorizontal(float step)
    {
        Vector2 direction = new Vector2(step, 0f);

        myRigidBody.MovePosition(myRigidBody.position + direction);
        yield return null;
    }

    public IEnumerator Animation_MoveVertical(float step)
    {
        Vector2 direction = new Vector2(0f, step);

        myRigidBody.MovePosition(myRigidBody.position + direction);
        yield return null;
    }
}

However since the animation events accept only functions with 0 or 1 parameters, I find it rather limiting to use them in place of the curves, so if somebody can think of a solution please let me know!


texts: What pattern is this, and should I do it?

texts:
I'm making a game in as3 using flash develop and flash cs5. Everything is object oriented. I was wondering, should I have one "gateway" class that has a property-reference to all instantiations of other classes, and I just pass this gateway class to new objects, so they have access to every class. Like so:

 var block:Block = new Block(gateway);

 //In the block class:
 this.gateway.player.setHealth(100);
 //Or:
 this.gateway.input.lock();

Is this like a singleton pattern or something? Should I do this?


texts: Is it safe to base a combo system in frames instead of time?

texts:
I'm building a prototype for a fighting game (not vs, something like Final Fight). I'm trying to define the data for the player combo tree and had a look around looking for inspiration and have seen games like Street fighter that base its combo timming on frames instead of time. The game is locked at a fixed frame rate too.

My question is, my game is targeting Windows, so, there are a lot of processes running in a computer. If I base my combo timmings on frames, can't a cpu spike produced by another process break my game?

A solution to fix this is to check every Update() how many real logic frames have passed (based that we want our game to run at 60 logic frames) and run the combo system all these number of frames at once. But not sure if this would work.

Beside all this, another problem is that Unity does not provide a separated thread for rendering and logic that could be configurable and accesible by the developer (It does not even have a frame rate independent input system shame).

Well, what do you think?

Cheers.


texts: How can I fix this shadow slicing the mesh on Android?

texts:
I have a golf ball in my Unity game for Android, which is an icosphere (imported from blender) with a baked normal map. There are 18 tracks located in one level around the (0, 0) coordinate, rotated in different directions.

The game uses Distance Shadowmask to create realtime shadows for near objects. In the editor and Windows builds, this works perfectly.

On Android, the shadow has a lower resolution, which is fine, but it seems to slice through the ball. It is visible in the following screenshot. If the ball moves, it looks like it passes through several planes casting a shadow.

This is heavily depending on the current track the ball is on. In 3 of the 18 tracks, there are very noticeable errors. Some other locations show very small errors.

However, those tracks are on seemingly random position. While the heavy errors appear on tracks located mainly in this (-x, -z) area, the small errors appear on arbitrary other positions.

I already tried:

changing shadowmap resolution
changing the directional light's near plane
changing the directional light's bias and normal bias
changing the directional light's position and rotation
rebaking the ball's normal map
using another ball mesh
removing the normal map from the material
using a different device


texts: Unity 5 Virtual Reality Supported: Text shimmering / aliasing in GearVR

texts:
I've spent the last 2 days trying to figure this out but have not come up with a conclusion. I'd appreciate if anyone has experienced the same and any thoughts.

Basically, I'm noticing that if I have a scene with text in it (world canvas and UI text component), when I build for GearVR with Unity's VR support, the text aliases like crazy. To be honest I'm not even sure 100% if it is plain old aliasing. The text just constantly shimmers.

I tried moving things around in case it was z fighting but it seems it is not.

I tried enabling anti aliasing from the quality settings and neither does it seem to make a difference.

I tried tweaking the Canvas Scaler Dynamic and Reference pixels/unit settings (which are not entirely clear to me from the docs btw). But at most, I was able to make the text slightly blurry as mentioned in the Unity VR guide and it barely helps.

I tried making the canvas and text huge and then scaling the canvas down to 0.05.

finally I tried making my text bold and bigger. And that seemed to mitigate the shimmering to a certain extent but not 100%.

But I've seen Unity apps for GearVR that don't exhibit this shimmering issue. So I am wondering what else might I be missing. I'm on 5.3.3.p3 if it makes any difference.


texts:
I see here that Hermite should be function in the class Mathf.

However, when I try to use it, the compiler tells me that Mathf doesn't contain a definition for Hermite.

This is an example:

    float fNewDistance = Mathf.Hermite(_initialDistance, _GoalDistance, fTime);

What am I doing wrong here?

Thank you!


texts:
I am trying to build a camera class, though I am running into a problem. When I move the camera above/below, and try to move towards the ground, I am moved off in what seems to be about 45 degrees in the YZ plane. Movement around the XZ plane seems fine. I do not see this effect when I am facing the cube from the side, it's likely just unnoticeable.

Here is the trig I'm applying:

public void moveForward(float amount)
{
    position.x -= amount * Math.sin(Math.toRadians(rotation.y));
    position.y += amount * Math.sin(Math.toRadians(rotation.x));
    position.z += amount * Math.cos(Math.toRadians(rotation.y));
}

public void apply()
{
    vMat.setIdentity();

    Matrix4f.rotate((float) Math.toRadians(rotation.x), new Vector3f(1, 0, 0), vMat, vMat);
    Matrix4f.rotate((float) Math.toRadians(rotation.y), new Vector3f(0, 1, 0), vMat, vMat);
    Matrix4f.rotate((float) Math.toRadians(rotation.z), new Vector3f(0, 0, 1), vMat, vMat);

    Matrix4f.translate(position, vMat, vMat);
}

I've tried using the 3D polar to component formulas instead of 2D. I've also tried swapping the cos/sin of various calls, all to less success.

For clarity, my intention is to be able to rotate any direction, and have movement operate along the cameras local Z axis.

How can I correct this?


texts:
How to create cocos2d v3.4 without using Cocos2D-SpriteBuilder?

I installed Cocos2D-SpriteBuilder as they recommended in cocos2d blog:

http://cocos2d.spritebuilder.com/get-started

But I need to create cocos2d v3.4 project from Xcode without creating it first in Cocos2D-SpriteBuilder.

Any help?


texts: Help with "Cannot find ContentTypeReader BB.HeightMapInfoReader, BB, Version=1.0.0.0, Culture=neutral." needed

texts:
I have this irritating problem in XNA that I have spent my Saturday with:

  Cannot find ContentTypeReader
  BB.HeightMapInfoReader, BB,
  Version=1.0.0.0, Culture=neutral.

It throws me that when I do (within the game assembly's Renderer.cs class):

this.terrain = this.game.Content.Load<Model>("heightmap");

There is a heightmap.bmp and I don't think there's anything wrong with it, because I used it in a previous version which I switched to this new better system.

So, I have a GeneratedGeometryPipeline assembly that has these classes: HeightMapInfoContent, HeightMapInfoWriter, TerrainProcessor. The GeneratedGeometryPipeline assembly does not reference any other assemblies under the solution.

Then I have the game assembly that neither references any other solution assemblies and has these classes: HeightMapInfo, HeightMapInfoReader.

All game assembly classes are under namespace BB and the GeneratedGeometryPipeline classes are under the namespace GeneratedGeometryPipeline.

I do not understand why it does not find it. Here's some code from the GeneratedGeometryPipeline.HeightMapInfoWriter:

 /// <summary>
    /// A TypeWriter for HeightMapInfo, which tells the content pipeline how to save the
    /// data in HeightMapInfo. This class should match HeightMapInfoReader: whatever the
    /// writer writes, the reader should read.
    /// </summary>
    [ContentTypeWriter]
    public class HeightMapInfoWriter : ContentTypeWriter<HeightMapInfoContent>
    {
        protected override void Write(ContentWriter output, HeightMapInfoContent value)
        {
            output.Write(value.TerrainScale);

            output.Write(value.Height.GetLength(0));
            output.Write(value.Height.GetLength(1));
            foreach (float height in value.Height)
            {
                output.Write(height);
            }
            foreach (Vector3 normal in value.Normals)
            {
                output.Write(normal);
            }
        }

        /// <summary>
        /// Tells the content pipeline what CLR type the
        /// data will be loaded into at runtime.
        /// </summary>
        public override string GetRuntimeType(TargetPlatform targetPlatform)
        {
            return "BB.HeightMapInfo, BB, Version=1.0.0.0, Culture=neutral";
        }

        /// <summary>
        /// Tells the content pipeline what worker type
        /// will be used to load the data.
        /// </summary>
        public override string GetRuntimeReader(TargetPlatform targetPlatform)
        {
            return "BB.HeightMapInfoReader, BB, Version=1.0.0.0, Culture=neutral";
        }
    }

Can someone help me out?


texts: Do industry professionals building games using UE4 use Blueprints at all, or do they use C++ exclusively?

texts: As a teacher on a game development module I have usually insisted that users use C++, because it is a more sought-after skill in industry, but online support and information on C++ in Unreal Engine 4 seems to be relatively weak. Are professionals now using Blueprints as well, or not?


texts: How to render many tiles fast if zoomed out? (Monogame/xna)

texts:
I'm currently trying to optimize my tile engine. I used monogame with the spritebatch first, but that doesn’t works well. I have read many articles how I could optimize my rendering code.

I moved away from the normal spritebatch and used the vertexbuffer+indexbuffer stuff. Works very well, but not so good as I hoped. I have chunked my tilemap in 50*50 large chunks and render each with his own vertexbuffer. Additional I check whether the chunk is in view and only render it then. But things are getting very bad if I zoom out.

Let’s say the map is 500*500 tiles where a tile is 32*32px tall. Now I must render too many of the chunks to the same time. How can I fix that performance issue here?

I have attached a sample project if some one is interested in it.
https://www.dropbox.com/s/2vbkng7ne6ey43e/TileEngineTestXnaMonoWpf.zip


texts: how update my game on google play(unity plus)?

texts: If I published  A game with unity plus license on google play (play store)so can  I update my game with unity Pro license Or I have to a  new create game o google play?


texts: How can City-sim simulate hundreds of characters?

texts:
My games usually start lagging quite easily when there are a couple hundred of boxes representing possible characters. While games like SimCity or even Anno have hundreds of characters.

I realized that those games don't update everything at every tic, the needs are handled in intervals and it's not a render problem, but all of those tiny creatures have individual path-finding etc.
I simply can't understand how they can pull that off for thousands of characters even on old machines. How do they do this?

This question was updated to refer to huge Numbers where individuals don't really count and are simply simulated for immersion and aesthetics.

(Related if referring to individual characters: How does Dwarf Fortress keep track of so many entities without losing performance?)

(Different question but maybe related?: Rendering hundreds of animated characters in Unity3D)


texts: How do I set the exact local position of a RectTransform?

texts:
I have a game object that creates a keyboard in side of my world canvas. I am working out the offset positions for each key, and appear to be doing that correctly. However, when I set the positions in the actual keys, the values are being offset by anything from 100 - 1000.

This is the basic method I am currently using to set the position:

public void SetDimensions(Vector2 position)
{
    GetComponent<RectTransform>().localPosition = position;
    Debug.Log(key + ": " + position);
}

I have also tried using .position and .anchoredPosition, as per the somewhat confusing API reference. I have also tried simply referencing transform.localPosition and transform.position. No matter what, the output is exactly the same. The debug output confirms that I am working out the correct local position, but no matter what I do, that is not the value being set to my transform.

As you can see, I have my pivot set to the center; though I think this may have an impact, it certainly should not cause an offset of 400-500.

As per request, this is my main canvas:

What am I doing wrong, or more specifically, how do I set the exact local position of a game object using a RectTransform?


texts: How can I spawn an object where I clicked in a 3D space, but spawn it in a 2D location?

texts:
I have a game where I have an object sat on a 3D plane and I want to click above it to drop an object.  Wherever I click I want the object to drop where I clicked on the Z-axis, but on a fixed position on the X and Y axis.

Please see the below image:

I am using the following code to do that, which I have attached to my long cube (the platform).

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class clickBehaviour : MonoBehaviour
{

    public GameObject GameCube;
    Ray ray;
    RaycastHit hit;

    // Update is called once per frame
    void Update()
    {

        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit))
        {

            if (Input.GetButtonDown("Fire1"))
            {
                GameObject obj = Instantiate(GameCube, new Vector3(-75, 9, hit.point.z), Quaternion.identity) as GameObject;
                Debug.Log(hit.point);
            }

        }

    }
}

GameCube refers to the GameObject of the smaller cube on top of the platform.

What seems to be happening, is that when the user clicks a block appears.  If the mouse is low down the screen on click then it appears where it should be.  If it is higher up the screen it appears off in one direction away from where it should be.

I believe this is because Unity is picking up the click way in the background, but I'm dropping the new cube in the foreground.  Because of this the Z coordinate is then quite a way off.  The further in the background I click the further off it is.

How can I have the cubes always appear in the correct position, above the platform?  I'm guessing this is a common requirement, but struggling to work out how to do it, or what to Google to find out more info.

Thanks


texts: In a HTML/JavaScript game, what audio should I use for Internet Explorer?

texts:
I'm planning some HTML5/Javascript games. They will be casual games for the most part, but would still benefit from music and sound effects. I would really like to use the <canvas> and <audio> features. I do not anticipate needing to play any movie files like .avi or .mp4.

But I run into a problem. According to this chart, Microsoft Internet Explorer does not support .wav or .ogg! And Safari doesn't support .ogg.

So now I'm making my own chart for what audio files I should use for what browsers. Here it is so far:

                     SFX        Music

Desktop Chrome      .wav        .ogg
Desktop Firefox     .wav        .ogg
Desktop IE          ???         ???
Desktop Safari      .wav        .m4a (alac)
Desktop Opera       .wav        .ogg

Mobile Chrome       .wav        .ogg
Mobile Firefox      .wav        .ogg
Mobile IE            ???        ???
Mobile Safari       .wav        .m4a (alac)
Mobile Opera        .wav        .ogg

(I could not find any info for Microsoft Edge on whether .wav or .ogg will work in the <audio> tag.)

As you can see, the big question lies in Internet Explorer. What audio formats should I use for sound effects and music?

It appears that HTML5 only supports 3 types: mp3, wav, and ogg. So for Safari I will need a plugin or some way to play .m4a music natively if possible. mp3 is out of the question due to absurd licensing fees. Flash/Shockwave is out of the question too.

I have read that something called bgsound can be used in IE, but it's "not standard". I've never used it before and don't know what it is.

So what audio formats should I use for IE? What is the "normal" way that IE plays sound and music in the first place? I really hope I don't need some plugin like Silverlight because those are a pain to users, especially casual game users.


texts: Pixelated and incomplete image when loading with pygame.image.load

texts:
This is the image I'm trying to load on the surface, an 40x40 Ubuntu logo:

Ans this is how it looks when trying to show the image on the surface via the blit method:

I'm trying to load different Linux logos, the majority have PNG extension and a couple of GIF. The Ubuntu logo is a PNG image, it's weird that the other PNG and GIF images load just fine (Ubuntu and Kubuntu logo are the exceptions, they look pixelated and incomplete).

This is how my code looks like (I'm just starting with pygame):

#-*- coding: utf-8 -*-
import sys
import os
import random
import pygame
from pygame.locals import *

PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
LOGOS_DIR = os.path.join(PROJECT_DIR, 'data/images/logos')
WINDOW_WIDTH = 640
WINDOW_HEIGTH = 480
FPS = 30

# Colors
WHITE = (255, 255, 255)

BACKGROUND_COLOR = WHITE

pygame.init()
MAIN_SURFACE = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGTH))
CLOCK = pygame.time.Clock()

def get_linux_logos():
    logos = []
    for img in os.listdir(LOGOS_DIR):
        try:
            logos.append(pygame.image.load(os.path.join(LOGOS_DIR, img)))
        except pygame.error, e:
            continue
    random.shuffle(logos)
    return logos

def main():
    pygame.display.set_caption('Geezle - Memory Puzzle')
    MAIN_SURFACE.fill(BACKGROUND_COLOR)
    LINUX_LOGOS_IMGS = get_linux_logos()[:12]

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        MAIN_SURFACE.blit(LINUX_LOGOS_IMGS[0], (300, 220))
        pygame.display.update()
        CLOCK.tick(FPS)

if __name__ == '__main__':
    main()


texts: What is causing a SIGSEGV in mono_class_vtable_full in Unity for Android?

texts:
I'm a developer of a mobile game, and we have Crashlytics in our game.

For the latest release for Android, we are having crash reports with the following stack trace, for a number of players:

Caused by java.lang.Error: signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 00000054
Build fingerprint: 'samsung/j7veltedx/j7velte:8.1.0/M1AJQ/J701FXXU6BRL1:user/release-keys'
Revision: '3'
pid: 10762, tid: 11403, name: UnityMain  >>> com.tod.xameen <<<
r0 00000000  r1 00000000  r2 00000001  r3 00000000
r4 d2145c4c  r5 00000001  r6 12f94a00  r7 12c80138
r8 00000000  r9 e674d600  sl 130bd128  fp d07ed36c
ip cfb4fbc4  sp d07ed350  lr cf9cf30c  pc cf9cf354  cpsr 0000004d

   at libmonobdwgc-2.mono_class_vtable_full(mono_class_vtable_full:180)
   at libmonobdwgc-2.mono_array_new_checked(mono_array_new_checked:132)
   at libmonobdwgc-2.mono_array_new(mono_array_new:40)
   at libunity.00520150(Unknown Source)

In our latest release, we upgraded a few of our external SDKs and libraries that may have caused this.

How can I find out the cause and fix it?


texts: 2D graphic over 3D perspective projection

texts:
To draw a 2D HUD (just a simple trianlge, for now) over 3D graphics in OpenGL I :

draw all 3D objects, then
call glDisable(GL_DEPTH_TEST) before drawing 2D HUD
draw 2D triangle
call glEnable(GL_DEPTH_TEST);

however it seems I am missing something and the triangle is only rendered when I set Model-View-Projection matrix to Identity :

DrawFrame() {
.
.. // Draw 3D objects
.
/*
*  Coordinates of 2D triangle
vert[0] = 0.0f; vert[1] = 0.5f; vert[2] = 0.0f;   // TOP
vert[3] = -0.5f; vert[4] = -0.5f; vert[5] = 0.0f;  // LEFT
vert[6] = 0.5f; vert[7] = -0.5f; vert[8] = 0.0f;   // RIGHT
*/

glDisable(GL_DEPTH_TEST);

glm::mat4 guiMVP = glm::mat4(1.0f);
//glm::mat4 guiMVP = Ortho * View * glm::mat4(1.0f);   // This does not render triangle
//glm::mat4 guiMVP = Projection * View * glm::mat4(1.0f);   // This DOES render triangle at its place but in 3D world
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &guiMVP[0][0]);
...
.. // render2D triangle
glEnable(GL_DEPTH_TEST);
}

OnSurfaceChanged(int width, int height) {

    glViewport(0, 0, width, height);

    aspect = (float) width / height;

    // Projection Matrix
    Projection = glm::perspective(45.0f, aspect, 0.1f, 10000.0f);
    // Orthographic Matrix for 2D HUD
    Ortho = glm::ortho(0.0f, (float)width, (float)height, 0.0f);
}

setCamera(float cameraX, float cameraY, float cameraZ, float cameraLX, float cameraLY, float cameraLZ) {
    // Camera/View matrix
    View = glm::lookAt(
        glm::vec3(cameraX, cameraY, cameraZ),     // Camera position
        glm::vec3(cameraLX, cameraLY, cameraLZ),     // pointing at
        glm::vec3(0, 1, 0)      // Angle
     );
}

here's my Vertex shader :

attribute vec3 in_Position;

uniform mat4 MVP;

void main(void) {
    vec4 v = vec4(in_Position, 1.0);

    gl_Position = MVP * v;

}

This is screenshot of what I want :

I DO get this output by using an Identity MVP matrix for 2D graphics. I know this is an ugly hack that works for now.

How to do this properly using Orthographic matrix ?


texts: Pick and Drop the Ball Testing Without Replicating the Physics Frame

texts:
I am making a program that pick, drag, and drop the ball. In real life, once you pick the ball and drop it, whenever the available object is (what you see is what you get) will only be picked and dropped again and again. However, in the game program, there is something that at first you did pick and drop the ball. When you did the second time, something hit like some sort of an "invisible object" and the physics frame (in pink) is replicating while the frame in green is the wall and the floor. Take a look at these pictures.

Before picking up and drop a ball for the first time...

When the ball in dropping... (Showing in pink frame for physics frame)

When picking up the second time, the previous pink physics frame did not come off and ended hitting something invisible.

So tell me, did I made something wrong in this touchDown() code or not? I have observed something here after I run in debug mode.

@Override
public boolean touchDragged(int screenX, int screenY, int pointer)
{
    // TODO touchDragged

    float change_x = (Gdx.input.getX()/(cv.getPhysicsCamera().viewportWidth))*5000;
    float change_y = (Gdx.input.getY()/(cv.getPhysicsCamera().viewportHeight))*15;

    x = ((change_x/cv.getPhysicsCamera().viewportWidth)/2) - (rc.getSoccerBallWidth()/2);
    y = (((cv.getPhysicsCamera().viewportHeight) - (change_y/2)) - (rc.getSoccerBallWidth()/2));

    Vector3 touch_point = new Vector3(change_x, change_y, 0);
    cv.getPhysicsCamera().unproject(touch_point);

    // Set new body frame.
    ballDef.type = BodyType.DynamicBody;
    ballDef.position.set(x, y);

    ballBody = wc.getWorld().createBody(ballDef);
    ballBody.setActive(false); // --> Allows you to display a cursor for dragging without letting your soccer ball to fall off while holding.

    return true;
}


texts:
I am able to scale an object using a scaling function I wrote. Internally it builds matrices that are multiplied by each of the vertices to transform them. The parameters I give the scaling function tell it how much to scale the object by as a factor of its current scale.

I want my object's scale to smoothly oscillate between two values, so I have used Sin waves to build my scaling factor, which is:

1 + amplitude * (Mathf.Sin(2 * Mathf.PI * frequency* Time.time) - Mathf.Sin(2 * Mathf.PI * frequency * (Time.time - Time.deltaTime)))

The result looks very close to what I want, but with each oscillation, the object gets slightly smaller than before.

The problem is that my function is written so that it scales the vertices as a factor of its 'current' scale, which is always changing.


texts: How can I change the hardness and blast resistance of Minecraft blocks?

texts:
I want to make the strength of the iron block and obsidian switch places, along with other changes to block strength and blast resistance. I am not allowed to swap the textures or anything like that. I need to actually change the values of each block.

To do this, I need to know where Minecraft stores the blast resistance and hardness.

Is decompilation required? If so, which class file do I need to look into?


texts: Handling rotation interpolation at 180 degrees

texts:
I currently have a scene where 3d a gents move throughout a grid, each time they move that can pick a random cardinal direction up,down,left or right. They then rotate to face that direction using Quaternion.Slerp. However I noticed there were some edge cases where the agents didn't move at all, and found out the problem was being caused during rotations at 180 degrees. Doing some reading on this I found that Slerp and Lerp dont handle rotations at this degree very well if at all and now I'm at a loss on how to proceed. I tried using transform.rotateAround() to rotate the character around the Y axis to the direction, but again at 180 degrees the agents start to just spin in circles forever.

Here's my current rotate code:

IEnumerator rotate(){
        while(Quaternion.Angle(transform.rotation,direction) > 0.3){
            var tempRotation = Quaternion.Slerp(transform.rotation, direction, Time.deltaTime * rotateSpeed);
            this.transform.rotation = tempRotation;
            yield return null;
        }
        this.transform.rotation = direction;
    }

Heres the code that handles picking where to go:

int choice = Random.Range(0,4);
        prevPos = pos;
        if((choice == 0) && pos.x < gs.maxX){
            pos.x += 1;
            direction = Quaternion.AngleAxis(-90,Vector3.up);
            }
            else if((choice == 1) && pos.x > 0){
            pos.x -= 1;
            direction = Quaternion.AngleAxis(90,Vector3.up);
            }
            else if((choice == 2)&& pos.y < gs.maxY){
            pos.y += 1;
            direction = Quaternion.AngleAxis(180,Vector3.up);
            }else if((choice == 3) && pos.y > 0){
            pos.y -= 1;
            direction = Quaternion.AngleAxis(0,Vector3.up);
        }

If someone could point me in the right direction on how to handle this gracefully I'd really appreciate it!


texts: How to make an object jump an equal height whenever it hits the ground?

texts:
So, I want to make an object jump an equal height whenever it touches the ground. Something like a bouncing ball. But I can't use Physics Materials. Here are some ways that I tried:
Used Physics.CheckSphere:
isGrounded = Physics.CheckSphere(rayPoint.position, grounDistance, groundLayer);

if(isGrounded )
{
    rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}

Used Raycast:
bool groundHit = Physics.Raycast(rayPoint.position, -transform.up, rayDistance, groundLayer);

if(groundHit)
{
    rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}

In each cases, the object jumps a different amount of height each time it reaches the ground. How can I make it jump an equal height each time?


texts: Why do I get a segmentation fault on launch with this code?

texts:
I am currently writing a pong clone in C++ with SDL on top. Currently, I have hit a roadblock. If I add a new variable, my game won't launch, and will give "segmentation fault" in the debug terminal.

When I comment out a variable, the following code gives no errors, but otherwise, it just returns "Segmentation Fault" on the debug terminal after flashing the frame the game would normally appear in.

#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif
#include "SDL/SDL_image.h"
#include "SDL/SDL_framerate.h"

#include "checkcol.h"

Uint8 *keystates = SDL_GetKeyState( NULL );

int main ( int argc, char** argv )
{
    // initialize SDL video
    if ( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }

    atexit(SDL_Quit);// make sure SDL cleans up before exit

    // create a new window
    SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16,SDL_HWSURFACE|SDL_DOUBLEBUF);
    if ( !screen )
    {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }

    SDL_Surface* left = IMG_Load("left.png");
    SDL_Surface* right = IMG_Load("right.png");
    SDL_Surface* ball = IMG_Load("ball.png");

    if (!left||!right||!ball)
    {
        printf("Unable to load a png: %s\n", SDL_GetError());
        return 1;
    }

    // centre the bitmap on screen
    SDL_Rect leftr;
    leftr.x = 0;
    leftr.y = (screen->h - left->h) / 2;

    SDL_Rect rightr;
    rightr.x = (screen->w - right->w);
    rightr.y = (screen->h - right->h) / 2;

    SDL_Rect ball1;
    ball1.x = ((screen->w - ball->w) / 2)+50;
    ball1.y = (screen->h - ball->h) / 2;

    SDL_Rect ball2;
    ball2.x = ((screen->w - ball->w) / 2)-50;
    ball2.y = (screen->h - ball->h) / 2;

    bool b1xm=0;//describes ball 1's movement in x
    bool b1ym=0;
    bool b2xm=1;
    bool b2ym=1;

    unsigned short lscore=0;
    unsigned short rscore=0;

    FPSmanager * manex;

    SDL_initFramerate( manex );
    // you want the top framerate to be 60 for example
    SDL_setFramerate( manex, 60 );

    // program main loop
    bool done = false;
    while (!done)
    {
                         //this is where my main code is
    } // end main loop

    // free loaded images
    SDL_FreeSurface(left);
    SDL_FreeSurface(right);
    SDL_FreeSurface(ball);

    // all is well
    printf("Exited cleanly\n");
    return 0;
}


texts: How do I implement Unreal-like object serialization?

texts:
Recently, I've been working on the core of my engine, and as I'm moving forward I find myself developing throwaway code to read files and simple data into the engine. This got me thinking about how I should implement a file management system.

After a bit of googleing I came across the Unreal Package format, and boy does it look like the perfect one.

I think it's good because the way how it allows you to separate different assets into different packages and allow something like a level to reference the different packages.

I was just wondering, is this possible with C#? Because the built-in serialization API in .NET does not seem to support any form of this, only reading and writing to a single file.


texts: How should the actual game interface with the menu system

texts:
I'm using the Game State Management (GSM) concept in my prototype and I like it very much. One of the screen has a "Game" embeded in it, where all the "good stuff" happens. The menu launching the game works fine, but I'm not sure how I should allow the game to request a screen from the ScreenManager. I'm not talking about a menu screen, but about something contextual to the game.

For clarity's sake, let's say that when I click on a game element (a rendered model for example) I want a screen that asks me what color I want that model to be drawn next. Right now, my game knows that model is "targeted" with the mouse (I use a Ray picking approach).

I looked at the Role-Playing sample to see how they did this, but when their GameScreen handles the keys, to open the inventory for example, it's never contextual to what's actually happening in the GameScreen.

Ideas welcomed!

Edit: The game must also be able to get a feedback or something from the "contextual screen" to get the new model color, for example.


texts:
I need to make a camera rotation system similar to the one here

http://madebyevan.com/webgl-path-tracing/

To rotate, press the Left mouse button and drag. So far I figured a basic idea of how this could be implemented.

Note that although it looks like the scene is rotating in front of the camera but in my case I want to rotate the camera instead. Since the scene contains hundreds of thousands of triangles and I wouldn't wanna apply a matrix operation to each of them.

I have represented my camera by a 4x4 matrix. The columns from 1 to 4 are side, up, look at and eye respectively.

So here's what I thought so far.

1) Subtract old cursor position from new cursor position. Doing this for X and Y we get a direction vector as to where the mouse is headed.

2) Invert this direction. And translate the camera a little in this direction. So if the mouse is headed right, the camera heads left. This is done by checking the components of the direction vector.

if (dir.x < 0)
    cam.eye += side
if(dir.x > 0)
    cam.eye -= side
if (dir.y < 0)
    cam.eye += up
if(dir.x > 0)
   cam.eye -= up

Note the translations are inverse. If less than zero than add the side vector instead of subtracting it.

3) Now find a vector perpendicular to it. So if the mouse was headed left or right the vector perpendicular to it is the Y axis. I calculate this by taking the cross(vec(0,0,1), direction_vector). Note this is not the inverse but the actual direction vector.

4) Rotate the camera a little along this perpendicular axis a little.

If you imagine these operations for the X axis. This feels like the camera is moving in some sort of circle around the scene. That is, the camera translates a little, then rotates. Next time it translates by adding the side (which was changed when it first rotated) it moves a little diagonally. In this way it feels like it rotates in a circle.

So this works somewhat fine for pure X and Y rotation and upto a certain extent. Fails when i move the mouse diagonally or in Pure X/Y rotation when I go beyond a certain point probably 90 degrees.

Any advice or suggestions? I am not using OpenGL instead doing this with GLFW and GLM. The renderer is a raytracer/pathtracer.


texts: XNA windows phone release black textures

texts:
i just made a 3d game in XNA for windows phone 7. I build it in release mode on visual studio 2010 and suddenly when I run game there is no textures on models - 2 models are black and one is transparent. Models are in .X format exported from 3dsmax and have textures in .jpg also added to game content. I set build action to none and all worked fine in debug mode. When I change to release mode - black textures. When I set build action to compile it gives me warning:

Asset was built 2 times with different settings: using TextureImporter and TextureProcessor using TextureImporter and TextureProcessor, referenced by...

and still no textures.

What can I do?


texts:
I try to create a button with the help of the NGUI. Here are screenshots of me doing that:

So the problem here is the next. When clicking play button in game mode I hope to get the following line in the console:

play.

But actually nothing happens. What am I doing wrong?


texts: How to design a leaderboard where lower is better?

texts:
In a classic high score leaderboard, the player with the highest score is leading, followed by people with slightly lower scores. In short, higher is better.

But in a game I am working on, the player has to reach the objective by completing various puzzles. The fewer puzzles he needs to solve before reaching his objective, the better. This is somewhat similar to fewest moves possible.

So basically, the leaderboard would be reversed, the player with the lowest score puzzles needed would lead the board, followed by players who needed slightly more puzzles to reach the goal.

How would I design/build the leaderboard so players understand the principle of lower is better?

Edit: One more important detail: The leaderboard will not be global, but local for one user, so he can track his own progress/improvement. So the design should be clear even if there are no entries yet.


texts: Should I distribute different versions of the same game for different mobile platforms?

texts:
I'm currently making a game on the Android platform. I don't know whether to do a "smartphone edition" and a "tablet edition" or simply to do one edition.

If I put high definition textures, the users of smartphones will have to download a heavy package, and thus will have very less space available as if it was "normal definition" textures. On the other hand, it's very hard to maintain two versions at the same time...

So how do you handle this? Even if you develop only for smartphones, do you send multiple versions of your game/app to the Android Market or not?


texts:
Is there any high level literature for mid professional programmers for Unity?
There are a lot of tutorials for beginners, but I can't find anything about main API, pipeline or engine architecture. Recommend, please!