texts: move along given path relative to the inital position

texts:
how can I move an object along a path "relative" to its inital position? I want it so if the object is initially positioned "around" the path instead of in the center, it will move along the path keeping that "displacement", as the below images

The blue line is the path and the red line is what the object, in this case the zombie, would follow if it had been initially positioned in the left and right sides of the "blue path", respectively:

Hope you understood. So far I've this

func move_zombie(delta):
    if target == null:
        return

    var target_pos = target.get_position()
    var pos = get_position()
    var dir = (target_pos - pos).normalized()
    var zombie_speed = 200.0
    position += delta * zombie_speed * dir


texts: Collision destroy a cube when player collides

texts: Unity- I have a mesh named and tagged as player I want that when it touches a Cube it should get destroyed C# script I need ....ty


texts: What is the actual formula to find the vertices of an animation frame in using a BVH file?

texts:
I've read this tutorial and tried many formulas to build the skeleton. I am able to build it without the rotations, but those break everything. This, for example, is a simplified code for one of my attempts:

/* Pseudocode using overloaded operators for illustration purposes */
var build_skeleton = function(motion,frame_number){
    positions = [];
    deg_to_rad = Math.PI/180;

    (function travel_tree(node,old_pos){
        pos = [node.offsetX, node.offsetY, node.offsetZ];

        frame = node.frames[frame_number];

        x_rotation = quat_from_axis_angle([1,0,0],frame[2] * deg_ro_rad);
        y_rotation = quat_from_axis_angle([0,1,0],frame[1] * deg_ro_rad);
        z_rotation = quat_from_axis_angle([0,0,1],frame[0] * deg_ro_rad);
        rotation = x_rotation * y_rotation * z_rotation;

        pos = old_pos + apply_quaternion(rotation, pos);

        positions.push(pos);

        node.children.map(function(a){ return travel_tree(a,pos); })
    })(motion.root,[0,0,0]);

    return positions;
};

I've tried many variations of this, switching axes, signals etc. Nothing seems to work. So what is the formula to find the positions of the vertexes of an animation on the BVH format?


texts: I would like to understand on a fundamental level the way in which A* pathfinding works. Any code or psuedo-code implementations as well as visualizations would be helpful.


texts: In order to create a day/night cycle in my game, I decreased the r,g and b values of the Color variable after a certain amount of time has passed. This worked as expected. I am wondering in order to create light from an item, like a fire or lamp, could I create a circle around the item and set the color in that circle to be white? Or is there a better way for accomplishing this in 2d?


texts:
I am kind of beginner with opengl.

I am using point sprites (currently without any texturing) for my particles. I seem to fail to get them uploaded to the GPU memory correctly. I have readed lots of tutorials on VBOs and VAOs and I can not locate the reason why the particles seems to be wrong.

The problem is, that some of the particles are behaving correctly, but others dont. They have random colors even if every one of them should be white and they are not in correct point in space. Also when a particle dies and the size of the array gets decreased, all particles warp in another location.

Here is my particle GPU data struct:

[StructLayout(LayoutKind.Sequential)]
public struct GPUParticle
{
    public Vector4 Position;
    public Vector4 Color;

    public static int SizeInBytes = Vector4.SizeInBytes * 2;
}

Here is the VAO, VBO and EBO initialization:

GL.GenBuffers(1, out Vbo);
GL.GenBuffers(1, out Ebo);
GL.GenVertexArrays(1, out Vao);

// Bind the VAO as current
GL.BindVertexArray(Vao);

// Bind the VBO to the VAO
GL.BindBuffer(BufferTarget.ArrayBuffer, Vbo);

// Describe the VAO data

GL.EnableVertexAttribArray(0);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, 0);

GL.EnableVertexAttribArray(1);
GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, 0, Vector4.SizeInBytes);

// Bind the EBO to the VAO
GL.BindBuffer(BufferTarget.ElementArrayBuffer, Ebo);

// Unbind the VAO
GL.BindVertexArray(0);

And here is the uploading which I do on every frame:

// Bind the buffer and send the data to the GPU
GL.BindBuffer(BufferTarget.ArrayBuffer, Vbo);

// Invalidate old data
GL.BufferData (BufferTarget.ArrayBuffer, new IntPtr(Count * GPUParticle.SizeInBytes), IntPtr.Zero, BufferUsageHint.StreamDraw);

// Upload new data
GL.BufferData (BufferTarget.ArrayBuffer, new IntPtr(buffer.Length * GPUParticle.SizeInBytes), buffer, BufferUsageHint.StreamDraw);

// Unbind
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

//Console.WriteLine ("Uploaded array buffer. Count: {0}", buffer.Length);

// Update index buffer only if there are more elements in the buffer than there has ever been
// Generate index buffer for EBO
indices = new uint[buffer.Length];

// This is really stupid. Perhaps we really do not need any indices?
for(ushort i=0; i < buffer.Length; i++)
{
    indices [i] = i;
}

// Bind the EBO for uploading
GL.BindBuffer(BufferTarget.ElementArrayBuffer, Ebo);

// Invalidate old data
GL.BufferData (BufferTarget.ElementArrayBuffer, new IntPtr(Count * sizeof(uint)), IntPtr.Zero, BufferUsageHint.DynamicDraw);

// Upload new data
GL.BufferData (BufferTarget.ElementArrayBuffer, new IntPtr(buffer.Length * sizeof(uint)), indices, BufferUsageHint.DynamicDraw);

// Unbind EBO
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

// Save the particle count for drawing and zeroing the buffer
Count = buffer.Length;

Here are the shaders:

#version 330 core
// VERTEX SHADER
layout(location = 0) in vec4 vertex;
layout(location = 1) in vec4 color;

uniform mat4 mP;
uniform mat4 mV;

out vec4 fragColor;
out vec4 pos; // For debugging

void main(){
    fragColor = color;
    pos = vertex;
    gl_Position = mP * mV * vec4(vertex.xyz, 1.0);
}

#version 330 core
// FRAGMENT SHADER
in vec4 fragColor;
in vec4 pos;

layout(location = 0) out vec4 color;

void main(){
    color = fragColor;
    //color = vec4(1,1,1,1);
    //color = pos;
}

I  have simplified the code a bit, but this is basically what I do. I am unable to spot what I am doing wrong.

The most weird thing is, that when in vertex shader I swap the color to be used as vertex and vertex to be used as color, the motion of the particles gets corrected, but the colors are still going haywire.

Any suggestions? I am out of ideas myself. Is the VAO initialization / uploading code correct?


texts:
I've been considering the idea of a game client that acted as a video compositor, only drawing, by itself, the terrain, the characters... deferring other graphic elements to separate processes. For instance, a health bar would be drawn by a separate process with its own address space and graphics context. Even if the mentioned bar could be drawn from another thread of the main process, or perhaps even from the renderer thread, this model would increase security (I believe it is already done in Chromium), ease development and the introduction of trivial and more complex addons, as well as make the whole game client, with all of its brethren, more balanced across threads/cores.
Please, note that the heavy rendering (i.e. terrain, characters,...) would be drawn from a thread of the main process on the entire window, so it wouldn't have to be composited. The compositor thread would then draw the contents of clients' graphics buffers on top of what the renderer thread drew, in their respective position.
Also, note that this is only a personal project, and that I have never developed a game. My target is Linux with Mesa. As for the IPC part, I had thought about Wayland.

Question(s)

Would compositing, and having multiple graphics contexts, degrade performance seriously?
Is this already done in any game client?

P.S.: I think World of Warcraft also uses addons, although I think they're in Lua and parsed from the main thread, so no compositing happens there.


texts:
Its a very simple question.
How can i rotate a line by one of its endpoints by the angle rad?

Heres my current code ( I couldnt find a different solution )

void displayPlayer() {
    float rad;
    putpixel(x, y, 10);
    if (view > 360)
        view = 0;
    nx = (int)round(x*cos(view) - y*sin(view));
    ny = (int)round(x*sin(view) + y*cos(view));
    rad = (double)view / 180.0 * M_PI;
    line(x, y,nx,ny);
    putpixel(cos(rad)*(x + 10) - sin(rad)*(y + 10), sin(rad)*(x + 10) + cos(rad)*(y + 10), 10);

}

Heres a litte visualisation of my result:

The line is supposed to be 10 px long and keep rotating 360°. Ive indicated its origin with a green line.

What am I doing wrong?


texts: Creating an interactive grid for a puzzle game

texts:
I am trying to make a slitherlink game, and am not too sure how to approach creating the game, more specifically the grid structure on which the puzzle will be played on.

This is what a empty and completed slitherlink grid would look like:

The numbers in the squares are sort of clues and the areas between the dots need to be clickable:

I would like to create the game in VB .NET. What data structures should I try to use, and would it be beneficial using any frameworks such as XNA?


texts:
I'm planning to write little 2D go-right-and-swing-your-sword game. When i started to write my ideas on paper i've come across a little problem.
Let's say i'm using magic spell, ex. fireball which technically is a signle projectile flying slowly in a specified direction. As it's defined to be a piercing projectile, I want it to hit every enemy only once, no matter how big their sprites are. And how I do it?
I know i can use the array of already hit enemies and check every frame if projectile collides something new, but is it a correct way? Are there any tried and true ways of resolving problems like this?


texts: How can I generate a TileSet from an existing image of a level?

texts:
Let say I have this level from Zelda: ALTTP.
I know that each tiles are 16x16. How can I generate a tileset and map from part of the original image?

(Image source)


texts:
I am having client/server application and i want to detect if client is alive.

So i know that send() will return me null but it will not inform my server that client has been disconnected.

Way i came up is each N seconds send "Are you alive" message from server to client but is that good solution?


texts: Does the standard lighting equation ever allow objects to be brighter than their textures?

texts:
It occurred to me that the standard lighting setup you see in all the tutorials doesn't allow lights to actually make an object appear brighter than its texture.  The light value is always clamped between 0 and 1.  Which means at maximum brightness, the resulting color will be exactly the same as the value from the texture.  Even if you didn't clamp it manually, in a deferred renderer, the graphics card/driver will end up clamping it for you.

This seems very unusual to me.  Do AAA games actually use lighting like this?  Or is there a solution?  My thought was maybe this is what HDR "fixes" but the only thing I've noticed HDR doing is that rather annoying light-transition effect.


texts: Are ClientRpc calls unsafe? How does a Unity server account for enforcing state concerning these?

texts:
I have recently picked up learning Unity3D's networking API, and have been following their multiplayer networking tutorial.
I just got to the topic "Death and Respawning" and am concerned about the safety of making ClientRpcs calls. From the article:

In our example the Client controls the position of the local Player GameObject. This is because the Player GameObject has local authority on the Client.
If the Server simply sets the Player GameObject’s position back to origin when the player’s currentHealth reaches 0, the Client would override the Server as the Client has authority.
To avoid this, the Server instructs the owning Client to move the player's GameObject to the restart position as a ClientRpc call. This position is then synchronized across all of the Clients because of the player GameObject's NetworkTransform.

So, does this mean that the local authority of the client could potentially override that of the server, and then subsequently have the server propagate incorrect updates to all other clients?
As an example, consider a player that has a "shoot" Command and can receive a "die" ClientRpc call. Let's say this player has been defeated fair and square, and the server sends the "die" ClientRpc call. But, consider that the player who died is a hacker who has rigged his/her local client to ignor this call. That player then issues a "shoot" command after s/he should have died. What would happen?
My guess is that the NetworkTransform component on the player is what dictates server authority over such instances, but I'm interested in knowing what is actually happening if not.


texts:
I can't understand what design pattern I can take advantage to build an intro screen, help screen, level select screen, game screen, game over screen, altogether.

I can make one in AS3, but the code becomes hugely messy.

That's what I sort of do. I would create a different class for each one but all classes don't share nothing in common, I just separate the classes to short the code in each file. The only parameter I pass on is stage as reference for all of them so that I can place the sprites and assets on the screen. I instantiate the game itself in a separated file and when the player reset the level that class would be re-instantiate or overwrite again. I run garbage collector in each class because there are some events I can't use reference.

Only I understand what I do, but as you can see it's certainly the wrong way since it has  became messy and hard to maintain. I learned by trial and error because I couldn't find examples showing how to code with OOP these layers or states(play, select, send score, play again and so on) of the game.


texts: AI of Turn Based game using Entity System approach

texts:
I just recently learned about Entity Systems and want to try it out on a real example (I was developing a game recently and want to try to port it over Entity Systems). But I got problem right away. Actually that is two questions in one.

First would be:

In traditional OOP approach I had game loop which was picking action to do for idling units every 100ms (so-called 'turn'). But rendering obviously was run at every game loop iteration. How should I do that? Maybe I need something like individual interval for systems to run? Like RenderingSystem running every Update while AI Systems are running each 100ms. Or maybe there is some better approach which I should use?

Second question would be about about these AI Systems

I understand how to make AI which will manage every unit completely individually. However I have somewhat simultaneous pathfinding for all units which will do:

Mark units that should start moving as 'moving'.
Find path for every 'moving' unit to it's target (basically closest enemy). All 'moving' units aren't considered as obstacles for path but all not-'moving' units considered as obstacles.
Try to move every unit one step at it's path. If can't make step (someone is already standing there) then mark path as invalid (to recalculate at next AI iteration) and move one step in direction of target (if there is free nodes).
Mark all 'moving' units as not-'moving'

Besides there is addition:
3. Before making step we will check if we have enemy around us and instead of moving we will attack that enemy.

So, one AI iteration required to give action to each unit which will be run until it finishes. Then AI should give next action.

How I can make that in Entity System approach? Because in ES all systems are run one-after-another where I need to "jump" beetween them freely. Or maybe I'm overcomplicating things and should do something different instead of "jumping" between systems?


texts:
How can I reset conditions for animations using an animation controller?

I have a door that will open when a boolean property in a script is set to true. This then calls setTrigger on the animator to play the open door condition and then reset the boolean property to false. After 5 seconds I then close the door. However when I change the boolean to true again to open the door, either the setTrigger isn't working again on the animator, or the trigger for the door close is conflicting. How would I resolve this? Is there a way in the animator to set a condition to false when a particular animation has finished? Initially I was using a boolean condition in the animator but ran into the same problem. I looked at the 2D sample project which used trigger instead and assumed this would only fire once. However I guess something else could be wrong. The code in my script is as follows: (where anim is the animator component)

   void Update(){
    if (open) {
        OpenDoor();
        open = false;
    }
}

void OpenDoor(){
    anim.SetTrigger ("OpenDoor");
    Invoke("CloseDoor",5);
}

void CloseDoor(){
    anim.SetTrigger ("CloseDoor");

}

As I say the animation fires correctly the 1st time but not on subsequent times. I'm just trying this by changing the public "open" property in the inspector

thanks


texts: If IDXGISwapChain::Present blocks, does that mean I'm GPU bound?

texts:
I updated my DirectX11 renderer to render on multiple threads using deferred contexts.  Before my change, the Present method took a negligible amount of time (according to VTune analysis).  After my change, Present now takes a significant amount of time (15-30ms or so).  I've tried using double / triple buffering, disabling vsync, but that makes no difference.  My scene runs at about 25 hz, and vtune shows my CPU at 100% up until i call Present, at which points it just waits for a good bit.

Does this mean that I'm GPU bound, or is this just an artifact of using deferred context rendering, since I'm not sending the GPU any work at all until the very last second?  And if its the latter, is there anything I can do to get started on the next scene rather than waiting around on Present?


texts: How to move on iTween path when a button is clicked

texts:
I have set the iTween path and also I have added a button. When I click on the button the object should start moving along the iTween path.But issue I'm facing is when I run my project at initial stage itself the object is moving on the iTween path which I  have set not on the button click. Then I tried out placing the same code for moving upon button click and it'S still not working. Can anybody help me solve this issue and provide me with a piece of code for it.
The code is here

void Start () {

    //iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("BoxOut"),"time",5));
    iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("Pass"),"time",50));

}

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

}

The above code worked initially, when the project started running, the object starts moving on the path. Then I edited the code and added the code on button click and it's not working anymore. The edited code is below.

void Start () {

    //iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("BoxOut"),"time",5));
    iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("Pass"),"time",50));

}

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

}
void OnGUI()

{
    if(GUI.Button(new Rect(100,100,100,100),"gggggg"))
    {
        Debug.Log("fffffffffffffffffffffff");
        resp=true;
    }
}

Its not working. Please help me out with a piece of code.


texts: Latitude and Longitude to Vector3 Not Aligning

texts:
I am trying to align a marker sphere to certain places on a bigger Earth sphere based on the inputted latitude and longitude.

The following is my code for this conversion, this code is based on the code here

void createLand()
{
    double radius = radiusEarth / 2;

    double latitude_rad = latitude * Math.PI / 180;
    double longitude_rad = longitude * Math.PI / 180;

    double xPos = (radius * Math.Sin(latitude_rad) * Math.Cos(longitude_rad));
    double yPos = (radius * Math.Cos(latitude_rad));
    double zPos = (radius * Math.Sin(latitude_rad) * Math.Sin(longitude_rad));

    // move ObjectMarker to position
    ObjectMarker.position = new Vector3((float)xPos, (float)yPos, (float)zPos);
}

radiusEarth = 6371f

I am also using a Mercator projection texture for my Earth object.

Here is what it looks like for the coordinates of London, UK, 51.509865, -0.118092.

As you can see, the marker is in almost the correct position but not quite there.

Here is what it looks like for the coordinates of Chennai, India, 13.067439, 80.237617.

As you can see here, the marker is completely off, it's been placed somewhere on top of Russia, although it does seem to be directly on top of Chennai.

Is there any way I can fix this and make the marker more accurate?


texts: Keeping per-client data, when using singleton-based states

texts:
In my game, I deal with a lot of units. Every unit implements a state machine, and changes states quite often. As a result, I'd like to keep my states as singletons, since I want to avoid the creation of one and the same state over and over again.

This works quite OK for most case, except when I need to introduce some time intervals, e.g. in 5 seconds the unit has do something. Of course, everyone knows that singletons cannot keep per-client data, which is exactly what I want to achieve. The state should be aware of the time elapsed since it was initiated for a specific unit.

One way to do this would be to keep timers within the units themselves, but that doesn't make a good abstraction.

Another one, which I am currently working on, is to keep the per-client state, i.e. timers on a Dictionary/Hash within the state. When a client initiates the state, the timer gets activated, and a dictionary record gets set. Every time when the specific timer is needed, the dictionary is queried with the id of the specific client. Then on state exit, the record is deleted.

Which is in general the proper way to deal with these problems?


texts: 2d grid vision(eye sensor) for a neural network bot?

texts:
I have a 2d grid and neural network bots living above it. What is a good way to give them vision of tiles in front of them?

Below I describe my idea that I don't know how to efficiently(or inefficiently) implement.

Bots can see other bots like in this video and it's already slowed my simulation, because I'm not so smart I guess and there is no code from this video available. I mean I've implemented it as good as I could and it doesn't bother itself with tiles, only with other bots. But due to the large amount of tiles to see in front of them and the fact that my bots can travel above them, I've decided to make a separate eye sensor just for tiles(soil, plants). No need to see other bots using this sensor.

My first idea was to get a cone vision, and I can get tiles inside this cone(triangle for simplicity) using triangle rasterization. BUT then I need to put all found tiles into 1D(or 2D doesn't matter) array that will make sense for my bots. And for that it must always be of the same size. And tile that is CCW to vision cone start and CW to another tile must always be between 1D array start and CW tile. And if tile is farther away from another tile inside cone(concentric circles), it must always be further away in 1D array.

But now I think it's too difficult and computationally expensive.

Shape of the vision cone is constant but number of tiles that fit with current rotation can differ. On this picture I check distance to the tile center and that center is inside using brute force approach, but I think during triangle rasterization it will differ as well.

On the picture you can see bot and his vision cone and 1D array I imagined. Null means that on this concentric arc could have been more tiles but in this rotation they are not inside. I don't know how to calculate number of tiles on each level. I think on the first always can fit only 1 tile and it's 0. On the second can be 1 or 2, now it's two(1,2). On third it can be 2(maybe more, I don't know how to calculate) tiles but now it's only one, number 3. etc.


texts: Efficiently culling off-screen objects on a top-down 2D map

texts:
I know efficiency is key in game programming and I've had some experiences with rendering a "map" earlier but probably not in the best of ways.

For a 2D TopDown game: (simply render the textures/tiles of the world, nothing else)

Say, you have a map of 1000x1000 (tiles or whatever). If the tile isn't in the view of the camera, it shouldn't be rendered - it's that simple. No need to render a tile that won't be seen. But since you have 1000x1000 objects in your map, or perhaps less you probably don't want to loop through all 1000*1000 tiles just to see if they're suppose to be rendered or not.

Question: What is the best way to implement this efficiency? So that it "quickly/quicker" can determine what tiles are suppose to be rendered?

Also, I'm not building my game around tiles rendered with a SpriteBatch so there's no rectangles, the shapes can be different sizes and have multiple points, say a curved object of 10 points and a texture inside that shape;

Question: How do you determine if this kind of objects is "inside" the View of the camera?

It's easy with a 48x48 rectangle, just see if it X+Width or Y+Height is in the view of the camera. Different with multiple points.

Simply put, how to manage the code and the data efficiently to not having to run through/loop through a million of objects at the same time.


texts:
I started playing around with terrain and I am getting this assertion in

QueuedRenderableCollection::addRenderable: "Error inserting new pass entry into PassGroupRenderableMap"

I am trying to find out what I have done wrong, but it is hard, so perhaps someone has any idea of what may it be.

I can reproduce it easily on my engine and my scene consists only of:

1 terrain page
1 mesh (highlander house)
1 directional light

If I reload the scene and look again at the house the assertion fires and it is very strange. I have tried to debug the code and the only reason for the assertion to fire that I have found is the hash being changed after the node was inserted on the map.

Any ideas how can I find a solution to it? Which data and information I can provide to help debug this?

Also I have seen in the forum some posts about this assertion, but no one that I have seen explain ways to debug or to fix it.

Ogre version 1.7.1
Windows 7
render Direct3d 9


texts: Why would this scaling matrix have no effect?

texts:
To draw a simple model using the DirectXTk, I'm doing the following.  It all works perfectly, draws correct, and so on.  Except changing the scaling factor makes NO difference, and I can't figure out why.

_MissileScale = 5.0f;
XMMATRIX GetWorldMatrix()
{
    XMMATRIX translation = XMMatrixTranslationFromVector(XMLoadFloat4(&_Position));
    XMMATRIX rotation    = XMMatrixRotationRollPitchYaw(_RotationX, _RotationY, _RotationZ);
    XMMATRIX scaling     = XMMatrixScaling(_MissileScale, _MissileScale, _MissileScale);

    return scaling * rotation * translation;
}

Then when I draw it, I ask for that matrix.  The rotation and translation work, but not the scaling.

        XMMATRIX mView = pCamera->GetViewMatrix();
        XMMATRIX mProj = pCamera->GetProjMatrix();
        XMMATRIX mWorld = pMissile->GetWorldMatrix();

        _ptrMissileModel->UpdateEffects([pCamera](IEffect* effect)
        {
            XMFLOAT3 ambientLightColor(0.5f, 0.5f, 0.5f);
            auto lights = dynamic_cast<IEffectLights*>(effect);
            if (lights)
            {
                lights->SetLightingEnabled(true);
                lights->SetPerPixelLighting(true);
                lights->SetLightEnabled(0, true);
                lights->SetAmbientLightColor(XMLoadFloat3(&ambientLightColor));
                lights->SetLightDiffuseColor(0, Colors::White);
                lights->SetLightDirection(0, pCamera->GetWorldAhead());
                lights->SetLightEnabled(1, true);
                lights->SetLightEnabled(2, true);
            }
        });

Any thoughts?  Of all the linear transformations you'd think scaling would be the hardest to get wrong!  I've tried the two "flailing" attempts of reversing my order of multiplication and of transposing the matrix before handing it off to the shader, neither helped (both broke the rendering as you'd expect).


texts: How to rotate an object based on the movement and angles of Lifters

texts:
I have Lifters that "carry" an object. I want the object to move and rotate based on how those Lifters move. Requirements include:

Supporting 1-4 Lifters at any side of the Object (e.g., both on one side, opposite, so on - can't make any guarantees about their positions relative to the object)
Supporting any orientation of the Object (e.g. the Object could be flipped on its side, sideways, or upside down; can't make guarantees that Forward is always facing forward, etc)

As such I implemented this by having the object move by setting its velocity to the average of the Lifters' velocity.
Now, if not all of them move (or if there's a disparity in their velocities), I want the object to rotate, like so:

This is done by keeping track of how much an individual lifter has moved in a frame from the Object's position, and calculating the angle via
m_Angle += Vector3.SignedAngle(lastPos - transform.position, currentPos - transform.position).

This "movement angle" I add up for every Lifter and then at the end, Rotate the Object via Transform.Rotate(Vector3.up, m_Angle).
However, this approach has some problems:

Calculations are done along the Y axis and therefore does not angle the Object up or down if the Lifters have different vertical positions,
m_Angle actually overshoots, but I found simply dividing m_Angle by the number of Lifters made it perfectly accurate. I do not know why this works.

Because I want this to rotate the object in "3 dimensions", I have attempted to calculate the "euler angles" of each Lifters' movement via:
Vector3 oldDisplacement = lastPos - transform.position;
Vector3 newDisplacement = currentPos - transform.position;
Quaternion rotation = Quaternion.FromToRotation(oldDisplacement, newDisplacement);
m_EulerAngles += rotation.eulerAngles;

And then at the end, I rotate the Object based on these "movement angles":
transform.Rotate(m_EulerAngles, Space.World);

This works in three dimensions, however it is off in the same way that m_Angle was before I divided it. It rotates the object too far. On top of that it seems to produce rotations along axes that have no displacement.

I want the object to only rotate exactly by the angle created by the Lifter's movement. This should keep it "synced" to Blue instead of rotating past as you see here.
When I check how much rotation Blue is adding per frame, I get an output like so:
Blue is adding (0.000, 359.507, 0.066); on movement (-0.015, 0.000, 0.000)

Despite moving solely on the x-axis, there is a z-euler angle being created, and the y-euler angle of 0.493 degrees is too much for -0.015f movement. I do not know why rotation.eulerAngles is inaccurate in my usage.
The only issue I can perceive is that since the Object's position is also moved at the end, the angle calculation assumes it is not moving and generates a larger angle (e.g., perhaps newDisplacement should be something like currentPos - (transform.position - m_Body.velocity * Time.deltaTime) ). However, removing the Object's movement from the finalPosition of the Lifter seemingly has no effect.
Or perhaps there is some finite precision in Quaternion.FromToRotation? Or my math is incorrect in some way?
I'd love a sanity check on the code or approach or if I should approach this problem from a different perspective.
EDIT: Here's an example gif of the functionality with m_EulerAngles code (so the rotation overshoots, but works in 3D - also I recorded the gif at lower fps that's not the game's framerate)


texts: How does one obtain an official Nintendo development SDK?

texts: I've seen before a topic here asking if there is any significant differences between using PALib or Nintendo's Nitro SDK... and that got me curious: what does it take to obtain the official SDK ?


texts: Unity3D: default parameters in C# script

texts:
Accordingly to this thread, it seems that default parameters aren't supported by C# script in Unity3D environment.

Declaring an optional parameter in a C# scirpt makes Mono Ide complaint about it:

void Foo(int first, int second = 10) // this line is marked as wrong inside Mono IDE

Anyway if I ignore the error message of Mono and run the script in Unity, it works without notify any error inside Unity Console.

Could anyone clarify a little bit this issue?
Particularly:

Are default parameters allowed inside C# scripts?
If yes, are they supported by all platforms?
Why Mono complains about them if the actually works?


texts:
How can you 'tile' a 3D globe if your existing artwork and maps are simple 2D grids?

Are there approaches that can re-use much of the artwork and such?


texts: How to continuously find all entities within a radius efficiently?

texts:
I have a very large number of entities (units).  On each step, each unit needs to know the positions of all units near it (distance is less then given constant R). All units move continuously. This is in 3D.

On average, there will be 1% of the total unit count near any other given unit with the given constraints.

How can I do this efficiently, without bruteforcing?


texts: How many views can be bound to a 2D texture at a time?

texts:
I am a newbie trying to learn on DX11.x. While reading about resources and views in MSDN, I thought this question
For a given 2D Texture created with ID3D11Texture2Dinterface (or for that matter any kind of resource), how many of following views can be bound to it?

1) DepthStencilView
 2) RenderTargetView
 3) ShaderResourceView
 4) UnorderedAccessView

Thanks in advance.
PS: I know the answer would be app specific, but still any insight into this would be helpful.


texts: What special requirements are there for making game art that supports High Definition? Does it require big changes in the way you model or texture your game objects? For instance, do models need really high resolution textures to support HD? If so, how high? And do you have to have a particular game engine that supports HD or would any game engine do? (I'm using Unity - would Unity work?). Also, are PS3 and XBox 360 the only platforms for HD or could PC and Mac handle HD games? Thanks.


texts:
In Unity3D how do I manage input among many components, especially in relation to "blocking" input messages to certain components?

To make my question clear, an example:

Component 1: Input Manager

Manages a list of components that require input. They do this via a Register method, which adds the component to a List. Each registered component can poll input via this method:

public static bool GetKeyUpAndActive(KeyCode keyCode, MonoBehaviour entity) {
    return Input.GetKeyUp(keyCode) && List.Contains(entity);
}

This feels clunky, as each entity needs to pass itself to the manager, and the manager has to keep a list of registered input events.

Component 2: Script Manager

Manages scripts such as "Open Dialogue Box, say "Hello", play SFX, add Item x to inventory. Script manager responds to input, for example, if over component, and Input.Action is pressed, run this script.

Component 3: Dialogue Manager

Manages the dialogue box, pretty stock standard stuff. It also responds to input, pressing Input.Action will cycle through the dialogue boxes, until it reaches the end, then returns back to the game.

The main issue I am facing is that the script manager and the dialogue manager are responding to the Input.Action during their own updates. So Script 001 responds to Input.Action which triggers an open dialogue box, but because dialogue manager also responds, it has already cycled through to the next dialogue box.

I think the Input Manager is breaking encapsulation. I also feel like I'm missing an obvious component here, maybe I need a stronger subscriber pattern to follow, or should there be a separate state manager, and if so, should the input manager only send events/provide methods to components in the correct state, or should components check the state machine themselves?


texts: How do I show an interviewer that I have past experience?

texts:
While researching some of the development companies I'd like to work for in the future, one thing kept catching my eye; they all wanted previous AAA experience I will have an enormous struggle obtaining. I currently live in an area with no AAA developers nearby, so an internship is next to impossible. Is this requirement a killer, or can this be looked past if I have an 8-year degree? (I am planning on getting a Masters in Computer Science or a similar field anyway for permanent job security.)

If this requirement is that important, I have also heard that you can compensate by having a homemade demo of a game you created on your own. If this is true, how complex must it be? As involved as an indie game? Deeper? Must it be in 3D?

I know this is a few questions too many for one post, but I'd appreciate any advice (preferably for people who have hired other developers in the past or have bypassed a similar issue.)


texts: Using result of ProjectWorldToScreen for DeprojectScreenToWorld does not produce initial input data

texts:
I am using this logic to project a point in world space into screen space.
const FVector Location = FVector(1, 2, 3);

FIntRect Rect;
Rect.Max.X = ViewportSize.X;
Rect.Max.Y = ViewportSize.Y;
FVector2D CurrentScreenSpaceCoords;

const FMatrix ViewProjectionMatrix = SceneView->ViewMatrices.GetViewProjectionMatrix();
SceneView->ProjectWorldToScreen(Location, Rect, ViewProjectionMatrix, CurrentScreenSpaceCoords);

I am using this code to get the initial value back
FMatrix const InvViewProjMatrix = ViewProjectionMatrix.Inverse();
FVector WorldPosition;
FVector WorldDirection;
FSceneView::DeprojectScreenToWorld(CurrentScreenSpaceCoords, Rect, InvViewProjMatrix, WorldPosition, WorldDirection);

However the result of DeprojectScreenToWorld does not produce the initial input (Location).
Instead of giving me the expected vector of [1, 2, whatever], it gives me X = [69.8139954,3840.00073, 250.49826]
Edit:
I am interested in X,Y. I don't need Z.
Somebody knows:

Why this happens?
How to get the initial value back from it

Thanks in advance


texts: Strategy for temporarily blocking user input

texts:
What are good approaches for disabling user input during certain moments in a game?
In my case, I have a grid-based tactics game (kind of like Fire Emblem) where I periodically want to toggle the user's ability to interact with the board. (For instance, the player may click a unit and then move it to a certain square; while the character is physically walking to the square, I want to disable user input). What's a good strategy for doing this?

Add a UI element that overlays the entire game, with a transparent image that blocks raycasts. Toggle this on and off as I want to disable user input.

Add a "locked" boolean and toggle the boolean. Then, for every function that processes user input, check if the "locked" boolean is true or not. This requires a lot of long-term maintenance so I don't prefer it.

???

Also, I'm using "OnMouseEnter", "OnMouseExit", etc. Would things be easier if I transition to this event system model, with things like "IPointerHandler"?
I'm looking for a solution that eases long-term maintenance and maximizes flexibility down the road.


texts: Unity - Moving RigidBody to a point in a spherical world

texts:
I have a planet ( a spherical planet) that have units on the surface , that units are attracted by the planet  with this

  public void Attract(Transform body,Rigidbody rigidBody)
    {
        Vector3 gravityUp =  (body.position - transform.position).normalized;
        Vector3 bodyup = body.up;
        Quaternion targetRotation = Quaternion.FromToRotation(bodyup, gravityUp) * body.rotation;

        body.rotation = Quaternion.Slerp(body.rotation, targetRotation, 50*Time.deltaTime);
        rigidBody.AddForce(gravityUp*gravity);
    }

I want them to also move to a specific point in the planet but I can't make it work, I tryed lot of things, the most "near" to the solution was this code on the Update method, but his make unit to "bounce",

Vector3 dir = (positionToAchieve - transform.position).normalized * speed;
rigidBody.velocity = rigidBody.velocity + dir;

Any idea /suggestion will be welcome, I am new in Unity and I am learning it


texts: Problem restoring the game preffered buffer size after navigating from a XAML page. Monogame

texts:
I have implemented to my game a simple leaderboard and submit score pages, which are pages in XAML. I used PreferredBackBufferHeight/Width to set the buffer to be equaly on all devices, whether their screen size is 5 inch, 4.7 or whatever size. Though I thought the problem was solved, now, when I was testing my game on emulator for bigger devices, I encountered a problem when returning back to game page from the xaml page. Let me show you some pics, and you will understand what I am talking about:

Testing on Emulator 4.7 inch:

1) Before entering the leaderboard xaml page (everything normal):

2) After exiting from xaml leaderboard page:

Even if I tried to put the PreferredBackBufferHeight/Width in the function that I call to exit from the leaderboard page, it didn't change anything... :

private void NavigateBackToMain()
    {
        var app = App.Current as App;

        if (app.GamePage == null) app.GamePage = new GamePage(string.Empty);
        Game1.statics.graphics.SupportedOrientations = Microsoft.Xna.Framework.DisplayOrientation.LandscapeRight | Microsoft.Xna.Framework.DisplayOrientation.LandscapeLeft;
        Game1.statics.graphics.PreferredBackBufferHeight = Constants.PrefferedBufferHeight;
        Game1.statics.graphics.PreferredBackBufferWidth = Constants.PrefferedBufferWidth;

        Window.Current.Content = app.GamePage;
    }

What can I do about my problem?


texts: Implementing Frame of reference for physics calculations

texts:
How would I alter physical calculations to account for frame of reference of a physical body?

Currently I have a world that is a collection of rigid body objects that act on each other. There is no frame of reference for collision detection or resolution with respect to each body (i.e. body A has a velocity of zero when resolving a collision with body B and vice versa). The world is the reference frame, therefore everything is moving that has a non-zero velocity.


texts: How to inherit of a scene tree structure in a way that a change in the ancestor is updated in the descendant?

texts:
Consider this structure:
* KinematicBody2D (Actor)
|_ AnimationPlayer (able to make a rotation of 360)

Now I want to make a Player and an Enemy that inherits of that structure in a way that when I change the animation on the Actor Scene, Enemy and Player are updated.
Is there a pattern that allows that?


texts: How can I move keyframes further apart in ToonBoom?

texts:
I've created an animation entirely out of screen capture fragments and keyframes, and I haven't allowed enough time for one portion.  I'd like to simply stretch out the time between two keyframes, pushing all other keyframes and exposures out to the right, but I can't see how to do it.

Here's a screenshot that shows my situation:

How do I do this?


texts: What is the point of the XNA.Input.Button enum?

texts:
I am trying to make an InputManager class that will let me basically bridge XNA's various input methods and do a corresponding action in my game. Part of this is designing different keybindings.

Suppose I have a class GamePadBinding : InputBinding<Button> - this is the Button enum from XNA.Input and has a variety of different buttons (Left, A, etc). However, to actually check input, I have to call something like if (GamePad.GetState(PlayerIndex.One).DPad.Left == ButtonState.Pressed), and the problem with that is that it uses a struct with readonly values.

How am I expected to store an enum of type Button and compare that with this? I really am not seeing the point of this enum.


texts: Collision between free player and tilebased map

texts:
so I'm working on some sort of platformer in javascript where the map is tilebased but the player can move freely.

Now, i have a problem with collision detection/response. It's kind of obvious what I'm trying to do, I don't want the player to walk into walls and fall into the ground so i need collision stuff.

Basic info:

The player is the same size as the tiles
The tiles are 8x8
The map is stored in an array like this: [0, 0, 0, 1, 1, 1, 0, 0, 0]. So if the map was 3x3 there would be a horizontal line in the center.

I feel that the system that I'm using is very inefficient and there are some problems with it:

sides = {};

// The tiles are 8x8 wide so i divide the players position by 8 to get the current tile the players is occupying.
// The player.y * mapWidth + player.x thing gets the tile at that position in the map array
// I use Math.floor instead of round to get the tile to the left of the player
if (map[(Math.round(player.y / 8) * mapWidth) + Math.floor(player.x / 8)] == 1) {
    sides.left = true;
} else {
    sides.left = false;
}

if (sides.left) {
    // Set the players x position to exactly outside the wall.
    player.x = Math.floor((player.x / 8) - 1) * 8;
}

Now this works fine for walls but when you use it on the ground it works but it glitches on corners.

For example if the player half way over an edge it falls through the tile and is pushed to the side.

Is there a better way to do this and if not, how do i fix the ground collision?


texts: What's an acceptable delay between a player's action and the effects of the action being visible?

texts:
So, I'm creating a game where all the systems push events onto the event queue. Those events are then dispatched at the start of the next frame. This works fine, but there are some situations where the delay between a player's action and the effects of the actions can be upto 3 frames.

3 frames for a 60fps is around 50ms. Is this kind of "lag" noticeable to a player?


texts: Why does Assimp appear to be loading vertices in the incorrect order in this code?

texts:
I'm getting a weird bug in my code that is reading in the vertices from an .obj file.

The .obj file is just a cube, hence there are eight vertices. When I print out the vector it seems to work perfectly up until the 5th vertex, and then it seems to read the last 3 backwards.

This is the file:

# Blender v2.69 (sub 0) OBJ File: ''
# www.blender.org
mtllib cube.mtl
o Cube
v 2.000000 -2.000000 -2.000000
v 3.000000 -3.000000 3.000000
v -4.000000 -4.000000 4.000000
v -5.000000 -5.000000 -5.000000
v 6.000000 6.000000 -6.000000
v 7.999999 7.000000 7.000001
v -8.000000 8.000000 8.000000
v -9.000000 9.000000 -9.000000
usemtl Material
s off
f 1 2 3 4
f 5 8 7 6
f 1 5 6 2
f 2 6 7 3
f 3 7 8 4
f 5 1 4 8

This is my code:

m->vertices = new glm::vec3[m->numVertices];
for (GLuint i = 0 ; i < m->numVertices ; i++) {
    const aiVector3D* pPos = &(mesh->mVertices[i]);
    m->vertices[i] = glm::vec3 (pPos->x, pPos->y, pPos->z);
    std::cout << "X:" << m->vertices[i].operator[](0) << " Y:" << m->vertices[i].operator[](1) << " Z:" << m->vertices[i].operator[](2) << std::endl;
}

However this is what is stored in the vector (what the above code prints out):

X:2 Y:-2 Z:-2
X:3 Y:-3 Z:3
X:-4 Y:-4 Z:4
X:-5 Y:-5 Z:-5
X:6 Y:6 Z:-6
X:-9 Y:9 Z:-9
X:-8 Y:8 Z:8
X:8 Y:7 Z:7

As you can see the last three lines are messed up, I have no idea how this is happening in the loop.


texts: Question About Scrolling A Tilemap In C++/SDL/OpenGL

texts:
I been working with scrolling this week but I recently encounter a problem that I don't understand why it's happening.

In a 2D scroller I want to scroll a tilemap pixel per pixel which gives a smooth scrolling in the game, but I encounter a weird problem, when the movement of the map corresponds with the exact size of the tile, for example, the map it's scrolling 32 pixels to the right, the map seems to jump to the next tile and not the one that corresponds correctly with the screen.

This is the code for drawing the map:

bool Tilemap::drawTilemap(GLfloat sizeTile, int indexTileset)
{
    offsetX++;
    if (offsetX >= 320.f) offsetX = 320.f;

    GLfloat widthTilesetImage = tilesetList.at(indexTileset).getWidthImage();
    GLfloat heightTilesetImage = tilesetList.at(indexTileset).getHeightImage();

    int widthMap = 40 + offsetX/32;
    int heigthMap = 23;

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnableClientState( GL_VERTEX_ARRAY );
    glEnableClientState( GL_TEXTURE_COORD_ARRAY );

    glBindTexture( GL_TEXTURE_2D, tilesetList.at(indexTileset).getTexture() );

    for (int i = 0; i < heigthMap; i++)
    {
        int startX = offsetX/32;

        for (int j = 0; j < 40; j++)
        {
            int frameIndex = layerMap[i][startX];

            if (frameIndex == 0)
            {
                continue;
            }

            frameIndex -= 1;

            const GLfloat tileX = 0.0f + ( (sizeTile)*j);
            const GLfloat tileY = 0.0f + (sizeTile*i);

            const GLfloat verts[] = {
                    tileX, tileY,
                    tileX + sizeTile, tileY,
                    tileX + sizeTile, tileY + sizeTile,
                    tileX, tileY + sizeTile
            };

            const GLfloat textureWidth = (sizeTile - offsetX/widthTilesetImage) / (GLfloat)widthTilesetImage;
            const GLfloat textureHeight = sizeTile / (GLfloat)heightTilesetImage;
            const int numFramePerRow = (GLfloat)widthTilesetImage / sizeTile;
            const GLfloat textureX = ((frameIndex % numFramePerRow) * textureWidth)+offsetX/widthTilesetImage;
            const GLfloat textureY = (frameIndex / numFramePerRow ) * textureHeight;

            const GLfloat texVerts[] = {
                    textureX, textureY,
                    textureX + textureWidth, textureY,
                    textureX + textureWidth, textureY + textureHeight,
                    textureX, textureY + textureHeight
            };

            glVertexPointer(2, GL_FLOAT, 0, verts);
            glTexCoordPointer(2, GL_FLOAT, 0, texVerts);
            glDrawArrays(GL_QUADS, 0, 4);

            startX++;

        }
    }

    glDisableClientState( GL_VERTEX_ARRAY );
    glDisableClientState( GL_TEXTURE_COORD_ARRAY );

    return true;
}

The variable offsetX it's the one that helps me move one tile at a time the map. The variable startX indicates when it's no longer drawing one tile, so in this one start in the next column of the matrix of tiles.

So, what could be wrong in my code?

Thanks for the help.


texts: Keep Mini map static after rotating / zooming with camera

texts:
Hi I am making a 2D game, where the Camera is able to rotate / zoom in or out on the camera focus (the player usually).

However my game also contains a mini-map, and so far whenever I have to rotate / zoom my camera the mini-map rotates and zooms accordingly. This behaviour was expected, but now I am a little stuck on "un-doing" the changes the view transformation has on my mini-map. What I want to happen is to essentially keep my mini-map statically in the same position throughout the game no matter how the camera rotates or zooms.

I am extremely rusty with my linear algebra / 3D transformations but I have tried the following...

My first thought was, I thought all I had to do was to transform the mini-map origin point with the view matrix, then undo the scaling of the zoom against the mini-map width / height. The zooming was fixed, but the mini-map still rotated so this did not work.

My second try, I remembered to undo the change of a matrix, I would have to multiply the transform by its inverse. So I tried to calculate the inverse matrix, however the determinant of the view matrix was 0, so I could not find an inverse.

Ok... well I guess I'll just see if I can get the rotation down, since I got the zoom to work... So I transformed my mini-map origin by the inverse rotation matrix applied by the view matrix... The mini-map is rotating now, but is not staying in the fixed position I was hoping for.

I was wondering, if anyone here can give me a push in the right direction, or a hint towards a more elegant solution overall. If people would like more information I can upload images, show code... But what I wrote above is exactly how my code would look.

Thanks for any help!


texts: Should I write my own game engine, and if so what are the main features?

texts:
Possible Duplicate:
  When to roll your own game engine?

I've been interested in writting games for a while, and now that I have acquired a bit of experience in programming, I feel like I could step up to making a little more complicated things. I've had some fun with SFML but since now I only had the basic classes I needed for my game objects, and a big run() method of my Game object to "run them all".

I've only written gameplay tests so far, but I feel like a complete game in the same style of programming would be a gigantic headhache source. I am now facing a problem/question : should I be considering creating my own little "game engine", learning through it, adding features as I need them ?
I think it could be a really good experience, but it would certainly take time as I'm no professional, and I don't have a clear view of "how-to" yet.

I am using SFML with C++.


texts: OpenGL texture 2d array won't render with depth > 1

texts:
Below code uploads my texture memory that's described in the passed parameters. When 'vPixelData' only holds 1 item/texture it is rendered properly, but once there's 2 or more nothing shows up.

glTexSubImage3D() is returning 'GL_INVALID_OPERATION' when I call glGetError() after it only when vPixelData.size() is greater than 1.

/*virtual*/ uint32 HyOpenGL::AddTextureArray(uint32 uiNumColorChannels, uint32 uiWidth, uint32 uiHeight, vector<unsigned char *> &vPixelData)
{
    GLenum eInternalFormat = uiNumColorChannels == 4 ? GL_RGBA8 : (uiNumColorChannels == 3 ? GL_RGB8 : GL_R8);
    GLenum eFormat = uiNumColorChannels == 4 ? GL_RGBA : (uiNumColorChannels == 3 ? GL_RGB : GL_RED);

    glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, eInternalFormat, uiWidth, uiHeight, static_cast<uint32>(vPixelData.size()), 0, eFormat, GL_UNSIGNED_BYTE, NULL);

    GLuint hGLTextureArray;
    glGenTextures(1, &hGLTextureArray);
    //glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D_ARRAY, hGLTextureArray);

    // Create storage for the texture
    glTexStorage3D(GL_TEXTURE_2D_ARRAY,
                    1,                      // Number of mipmaps
                    eInternalFormat,        // Internal format
                    uiWidth, uiHeight,      // width, height
                    static_cast<uint32>(vPixelData.size()));

    for(unsigned int i = 0; i != vPixelData.size(); ++i)
    {
        // Write each texture into storage
        glTexSubImage3D(GL_TEXTURE_2D_ARRAY,
                        0,                                      // Mipmap number
                        0, 0, i,                                // xoffset, yoffset, zoffset
                        uiWidth, uiHeight, 1,                   // width, height, depth (of texture you're copying in)
                        eFormat,                                // format
                        GL_UNSIGNED_BYTE,                       // type
                        vPixelData[i]);                         // pointer to pixel data

        GLenum eError = glGetError(); // Getting 'GL_INVALID_OPERATION' when > 1 texture depth. It's 'GL_NO_ERROR' otherwise
    }

    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    return hGLTextureArray;
}

(My current passed parameters are uiNumColorChannels == 4)

(uiWidth and uiHeight are both 512)


texts: What use for a 3d browser based multiplayer online game?

texts: Can you help me choosing the right tools for this project? It's a 3d browser based multiplayer online fighting game. A few 3d functions are necessary for positioning, but no heavy rendering will happen. It needs very low ping rates, though, as it will be very dynamic. HTML5 + three.js + some networking lib seems like a fair choice, but I'm concerned about performance and cross-browserism. It's for learning purposes but I can use it for professional showoff. Thoughts?


texts:
I'm currently tasked with porting a control from Direct 11 to DirectX 12.

How do I draw text on the screen?

How do I draw any 2D on a DirectX 12 device?

Current Text rendering code is below:

using (var textFormat = new TextFormat(device2DManager.DirectWriteFactory, string.IsNullOrEmpty(text.FontName) ? FontName : text.FontName, text.FontSize == 0 ? FontSize : text.FontSize))
                {
renderTarget.DrawText(text.Text, textFormat,
                            new RawRectangleF(autoPosition.HasValue ? autoPoint.X : text.Location.X, autoPosition.HasValue ? autoPoint.Y : text.Location.Y,
                                renderTarget.Size.Width, renderTarget.Size.Height),
                            foreColor);
}


texts:
I'm using Ogre 1.10, I have a dynamic texture assigned to a material that I need to update its buffer with a new image every few seconds.
How can I transfer pixel data from an image to my dynamic texture?

I've created a manual texture like:

         // Create the texture
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(
            "dyn_texture", // name
            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
            Ogre::TEX_TYPE_2D,      // type
            256, 256,         // width & height
            0,                // number of mipmaps
            Ogre::PF_BYTE_BGRA,     // pixel format
            Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);

And on my update function I have the image that I want to transfer:

Ogre::Image img;
img.load(basename.toStdString(), "resources");
//Copy pixels from img to texture
//??

I've already tried doing:

Ogre::HardwarePixelBufferSharedPtr pixelBuffer = texture->getBuffer();
pixelBuffer->blitFromMemory(img.getPixelBox());

works but it's quite slow, gui freezes when updating like that.


texts: How can I mark levels as "complete" in a way that prevents cheating?

texts: My first thoughts about marking levels complete is to just write the information to a file upon level completion and load that in once the app is opened up again. But how could I keep this safe from tampering and prevent cheating?


texts:
I want to make a collider for a line that I've drawn on the screen using mouse. so the detection should be cover the whole line that has drawn.

What I've learned from edge collider is you can have collider if you assign the position of a certain point in col.transform.position (for example I can assign the startpos of my line and the collider works only for that point).

the green line which is drawn by mouse in front of car is using the LineRenderer and requires EdgeCollider to be a road that car can drive on it's surface

and my functions:

private LineRenderer line; // Reference to LineRenderer
private Vector3 mousePos;
private Vector3 startPos;   // Start position of line
private Vector3 endPos; // End position of line
public Material material;

void Update()
{
    // On mouse down new line will be created
    if (Input.GetMouseButtonDown(0))
    {
        if (line == null)
        {
            createLine();
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            line.SetPosition(0, mousePos);
            startPos = mousePos;
        }
    }
    else if (Input.GetMouseButtonUp(0))
    {
        if (line)
        {
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            line.SetPosition(1, mousePos);
            endPos = mousePos;
            addColliderToLine();
            line = null;
        }
    }
    else if (Input.GetMouseButton(0))
    {
        if (line)
        {
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            line.SetPosition(1, mousePos);
        }
    }
}
// Following method creates line runtime using Line Renderer component
private void createLine()
{
    line = new GameObject("Line").AddComponent<LineRenderer>();
    line.material = material;
    line.SetVertexCount(2);
    line.SetWidth(1.1f, 1.1f);
    line.SetColors(Color.black, Color.black);
    line.useWorldSpace = true;
}
// Following method adds collider to created line
private void addColliderToLine()
{
    EdgeCollider2D col = new GameObject("Collider").AddComponent<EdgeCollider2D>();
    col.transform.parent = line.transform; // Collider is added as child object of line

    col.points[0] = startPos;
    col.points[1] = endPos;

    Vector3 midPoint = (startPos + endPos) / 2;
    col.transform.position = midPoint; // setting position of collider object
    // Following lines calculate the angle between startPos and endPos
    float angle = (Mathf.Abs(startPos.y - endPos.y) / Mathf.Abs(startPos.x - endPos.x));
    if ((startPos.y < endPos.y && startPos.x > endPos.x) || (endPos.y < startPos.y && endPos.x > startPos.x))
    {
        angle *= -1;
    }
    angle = Mathf.Rad2Deg * Mathf.Atan(angle);
    col.transform.Rotate(0, 0, angle);
}

btw i don't know what that col.points[] used for. I just found it from the unity documentation which won't make any collision


texts: FB.Init() is not accepting in my c# Script

texts:
I am trying to connect fb with my game. its first time i am connecting fb with game. i downloaded fb SDk  7.3.0 and i am using unity 5.2.1f1. i imported the sdk in my game asset. then i created a new c# script "FBholder". in Awake() i tried to use FB.Init(). but its not accepting. all other scripts used inside the game are calling correctly, only the scripts came with fb sdk is not working.

 using UnityEngine;
 using System.Collections;

public class Fbholder : MonoBehaviour {

// Use this for initialization
void Awake() {
    FB.Init (SetInit, OnHideUnity);// This line is not accepting
}
}

i Used this Video for my referance


texts: Why wont the LibGDX's main class Initialize on Android Launcher?

texts:
So I was searching for different ways that could suit me in programming and came across LibGDX.  Naturally I looked at the tutorial.  As I was doing it, I was following the steps word for word, except naming the classes.  In the end, I was able to create the desktop launcher for the game but not the android launcher.

The following error is my error: Cannot instantiate the type Game
(Game is the name of the class)

I got the tutorial from
http://steigert.blogspot.com.au/2012/02/1-libgdx-tutorial-introduction.html
The link in the tutorial is the original but it uses jogl instead of lwjgl.


texts:
I am working on an old-school platformer in libgdx and I want it to have a "scanline" effect, like this:

My first attempt was to make a little texture and draw it on a full-screen quad. I used two different orthographic camera modes (one for the main tilemap of the game, and a second to render the scanline texture). Sometime the texture is stuck on the tilemap and sometime it is too large, and covers the whole screen in black.

Is my approach using two cameras and a texture reasonable? What's a good solution to achieve this effect?


texts: Unity - Ignore mouse click outside of the UI

texts:
I am having a problem with my in game UI menus like the pause menu.

When I hit the escape key the mouse cursor and pause UI is shown with 2 buttons "Continue" and "Exit". I have locked the player from moving when this UI is shown. But when I click outside of the buttons the mouse disappears and the player can move once again, the UI is still shown but it's lost focus or something.

Is there a simple way to stop this? I've seen some scripts which seem to try to catch this behavior and ignore the click but I'm hoping there is a property on the canvas or something that I can use built into the engine.

Thanks, Sam


texts: How can I build an array of coordinates of a truncated icosahedron's faces?

texts:
I can easily get a list of coordinates of all the vertices—the Wikipedia page has formulae and this page has a list of them, but that doesn't tell me which ones are part of which face.

What I'd like is to create an array of 32 faces, and for each one have:

The 3-coordinate of the center of the face
The rotation of the face about the center point
Whether it's a pentagon or a hexagon

How can I generate that data?


texts: In Theory, how much gain should I expect from instancing in OpenGL for small scene with large meshs?

texts:
I am trying to implement one-pass stereo rendering in OpenGL for a VR application that I am building. I am implementing this through instancing, so I make one render call glDrawElementsInstanced with count=2 and do clipping in the vertex shader but I am not seeing that much gain in performance.

My scene has just 2 massive meshes (rendered two times (2 instances), one for each eye totaling around 3.5m triangles for each eye or ~7m per frame). Obviously I can reduce the triangle count by doing some decimation but my question here is,

In theory, should I expect a significant gain in performance by using instancing in this scenario even though the number of draw calls and state changes in the entirety of my application is around 15 per frame For each pass and 30 per frame?

Or to Rephrase the question, Does OpenGL instancing improve performance mainly by reducing state changes or by making less calls to glDraw*?


texts: How can you check your users' unlocked achievements (Google Play Game Services)?

texts: Is it possible to see how many of your users have unlocked certain achievements on the Google Play Developer console? This information would be very useful. I guess that one could achieve this through integration with Google Analytics but I was wondering if there was a simpler way to get this data.


texts: Loading scene doesn't reactivate gameobjects

texts:
I have some levels and a main menu. When starting the game from the main menu (in the editor debug mode) I can select a level a load it, no problem. However, when I wish to go back to the main menu using

SceneManager.LoadScene(index);

A whole lot of my gameobjects throw exceptions like

  The gameobjects is destroyed, but you are trying to access it

and

  Missing reference exception

and so on.

However, when i start the level from the editor (and not using the main menu), I can go back to the main menu, it works as it should.

NOTE that I don't have any persistent gameobjects. I do have singletons, but no persistence here. Any ideas what could cause the issue?


texts: How should I share variables between instances/classes?

texts:
I'm making a game using LOVE, so everything is programmed in Lua. I've been experimenting with using classes and object orientation recently. I've found out that a nice system to use is having most of the game's code in different classes, and having a table of instances with all of the instances of any class in it. This way, I can go through every instance of every class and update and draw it by calling the same function.

There is a problem, though. Let's say I have an instance of a player with variables for health and recharge time of a weapon. I also have a master instance which is responsible for drawing the HUD. How can I tell the master instance what the player's health is? Bad solutions:

Assuming that the player instance will always have the same position in the table - that can be easily changed.
Using global variables. Global variables are evil.
Have the master instance outside of the instances table, and have the player set variables inside the master instance, which it then uses for HUD drawing. This is really bad because now I have to make a duplicate of every variable the master instance needs.

What is the proper, standard way of sharing variables between instances? Do I need to change the way I keep track of instances?

Edit: the hump library for LOVE has a signal/slot system. Would that be a reasonable way to share variables between instances?


texts: How do you technically represent a procedurally-generated map in the scene?

texts:
I've always wanted to create the type of map generator they use in Kingdoms and castles. Basically you provide a seed, and it generates land/water/trees/resources. Their maps are also completely flat (except water seems to be 1-2 positions down, which I assume would make it easier.

However I do not know where to look for guidance for this type of system, I am wondering if anyone can explain the logic of how that type of system works, or even better, point me to a tutorial that could get me started.

While there are tutorials on perlin noise and the like, I never really understood how to connect it to a proper tile, and what properties that tile should have, does it need colliders? is each tile a gameobject? If not, how do I create tiles with trees/rocks that I can gather? and so on.


texts: Linear filter problem with diagonal lines on adjecent tiles

texts:
I am quite new at using OpenGL/GLSL. Basically, the project I am working on is my first 'real' experience with it.
I do not know whether this is relevant, but I use libgdx for my project.

Currently, I am trying to use the GL_LINEAR filters to draw tile of my (tile) map (before I was using GL_NEAREST without problems).

My map contains diagonal roads (just simple lines in this example). A partial overview/example of my map (using the nearest filter without corrections):

With the GL_NEAREST filter, initially I added a 1 pixel border, so the tiles were slightly overlapping and the diagonal roads were draw without the small gaps at the edges of the tiles.

This does not work with the GL_LINEAR filter, because I suppose that the overlapping parts are drawn twice, resulting in a darker 'blob':

I tried to get rid of the blobs, by making the horizontal lines shorter, but there is always an irregularity, either a blob or an 'decrease of line width' (as seen in the diagonal part of the line).

So I removed the 1 pixel additional border and have this as a result:

Now I am trying to fill in the 'gaps' by drawing the two triangular fillers like this:

but I can't get it completely right (this is the best I managed to get):

I suppose it is virtually impossible to get this perfectly right by 'manually' drawing these triangles. Also, when looking at the third image, the lines at the 'edges' (that need to be filled) are very sharp. I suppose this is problematic..?

So, my question is: how does one solve this problem? Do I need to prepare/modify my textures for this? Can I use a shader to fill the gaps automatically? Is manually filling the gaps with the triangles the way to go? Or is there some entirely different technique to have smooth diagonal lines that span multiple tiles?


texts: Is creating a blend state like this possible?

texts:
I'm wanting to create a custom blend state that is similar to XNA's BlendState.Additive, but slightly different. I'm wanting something like the 'custom' output below:

Is something like this possible? I'd even appreciate an answer that could help point me in the right direction. Blend states are a little bit baffling to me at the moment.

For an explanation of why I need this: I'm trying to add emissive maps to our game's rendering. I think most shading that uses emissive maps handle that in the lighting shader. Unfortunately, the emissive maps aren't available to our lighting shader, so I'm just trying to draw them over the top of what's already been rendered. Using BlendState.Additive almost works, but doesn't handle situations where emissive textures are overlapping.

Thanks in advance.


texts: Unity - I can't change the "colorOverLifetime" property of the "Particle System" via script

texts:
The goal is to remove the particles via script with fade effect. But I'm not just interested in an alternative, I want to understand why my code doesn't work.

The code below is modified to show only the important parts. I can't know before what time the particles will be dissolved, so I can't set the parameter from the editor.

StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys
This is the important point (see the log image). The gradient does not take my new values but alphaKey is correct.

Why ?
Thanks

private bool FadeStarts = false;

void Update()
{
    if (FadeStarts) return;
    StartCoroutine(fadeStars(false));
}

private IEnumerator fadeStars(bool show)
{

    FadeStarts = true;

    ParticleSystem.ColorOverLifetimeModule c = new ParticleSystem.ColorOverLifetimeModule();

    c = StarsConfig.Stars.colorOverLifetime;

    Gradient g = c.color.gradient;

    Debug.Log("OFF " + c.color.gradient.alphaKeys[0].alpha + " --> " + g.alphaKeys[0].alpha);

    GradientAlphaKey[] alphaKey = new GradientAlphaKey[2];
    alphaKey[0] = c.color.gradient.alphaKeys[0];
    alphaKey[1] = c.color.gradient.alphaKeys[1];

    while (c.color.gradient.alphaKeys[0].alpha > 0f) {

        alphaKey[0].alpha -= StarsConfig.VelocityAlpha * Time.deltaTime;
        alphaKey[1].alpha -= StarsConfig.VelocityAlpha * Time.deltaTime;

        StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(c.color.gradient.colorKeys, alphaKey);

        Debug.Log("g " + alphaKey[0].alpha + " --> " + StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha);

        /*
        StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(
            new GradientColorKey[] { new GradientColorKey(Color.white, 0f),
                                    new GradientColorKey(Color.white, 1.0f) },
            new GradientAlphaKey[] { new GradientAlphaKey(StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha - (StarsConfig.VelocityAlpha * Time.deltaTime), 0f),
                                    new GradientAlphaKey(StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[1].alpha - (StarsConfig.VelocityAlpha * Time.deltaTime), 1f) });

        */

        yield return 0;
    }

    StarsConfig.Stars.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);

    FadeStarts = false;
}

UPDATE

Ed_Marty's suggestion is correct, and the solution is there (thanks!). But I would like to understand what is the difference between these two codes.

This code works

var col = StarsConfig.Stars.colorOverLifetime;
while (col.color.gradient.alphaKeys[0].alpha > 0f) {

    float alpha = StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha - (StarsConfig.VelocityAlpha * Time.deltaTime);

    Gradient grad = new Gradient();
    grad.SetKeys(
        new GradientColorKey[] {
            new GradientColorKey(Color.white, 0.0f),
            new GradientColorKey(Color.white, 1.0f) },
        new GradientAlphaKey[] {
            new GradientAlphaKey(alpha, 0.0f),
            new GradientAlphaKey(alpha, 1.0f) });

    col.color = grad;

    yield return 0;
}

And this doesn't work

while (StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha > 0f) {

    float alpha = StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha - (StarsConfig.VelocityAlpha * Time.deltaTime);

    StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(
        new GradientColorKey[] { new GradientColorKey(Color.white, 0f),
                                 new GradientColorKey(Color.white, 1.0f) },
        new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0f),
                                 new GradientAlphaKey(alpha, 1f) });

    yield return 0;
}


texts: How do I compile a C# script at runtime and attach it as a component to a game object

texts:
The idea here is to let users program the behaviour of an agent in a way that reminds of the "Screeps" game, where you get to develop code which later runs and dictates the behaviour of your units.

My idea is to let users develop the behaviour or their units with C# code, compile that code at runtime and attach it as a MonoBehavior to an existing game object.

How can I achieve this?


texts: How to manipulate the two variables that rotate the camera with Input.GetAxis(“Mouse X/Y”)?

texts:
A helpful fellow showed me the script for a free look camera mode that rotates with the mouse. The script is included at the bottom of the page.

I want to have a system that right clicks once to enter this camera mode and right clicks again to exit it and slerps back to the original position. I tried to do it, but it seems like when I right click once and then right click again, it works ok because it's the first time I do it. But when I right click again, it snaps back to the rotation that it last left off from in free look (the starting rotation of the slerp).

Does this have to do with the way the yaw and pitch variables are stored? I assume that after exiting free look, yaw and pitch still hold the values from the last rotation. Consequently, I tried resetting yaw and pitch, but it still has the same old problem.

On the other hand, after playing around a bit, sometimes it resets to a particular rotation no matter what. So does that mean I need to do a bit of testing and say,

if (rotation = x)
{
    pitch = y;
} // figure out what y should be through trial and error testing)

or something like that?

using UnityEngine;
using System.Collections;

public class FirstPersonCam : MonoBehaviour {

    public float speedH = 2.0f;
    public float speedV = 2.0f;

    private float yaw = 0.0f;
    private float pitch = 0.0f;

    void Update () {
        yaw += speedH * Input.GetAxis("Mouse X");
        pitch -= speedV * Input.GetAxis("Mouse Y");

        transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
    }
}


texts:
We have managed to create grayscale picture using the following snippet of codes in SDL. What we need to do now is how to first convert into YUV or YCrCb for it be able to set the luminance value and thereafter back into RGB?

const unsigned int gray = (component1 + component2 + component3) / 3;

const int gray_rgb = SDL_MapRGB(original->format, gray, gray, gray);


texts:
My game is very GUI based, the way how it works is that I have a GUI class, which contains the basic GUI elements, a parent GUI object, and a copy of the main game's class object. The game starts out with the main GUI, which is the main menu, then when it wants to it takes something like the in game GUI, creates a object with the main menu's copy of the game and then the main menu object itself using this as the parent GUI. So when the in game GUI wants to, it can call back for the parent GUI to be used again.

Here is where the issue lays, the in game GUI needs to be a GUI, but also needs to contain this such as the level it's playing, the player, and all those things. How is this done?

Should I have approached my GUI based system differently? Because I can't somehow figure out of I would implement such a GUI without errors. How do you approach this? Or how would you approach this?


texts: Need help implementing shadows on platform with limited feature set

texts: I am writing a game that very much relies on real-time shadowing and would like to implement shadow volumes. I was thinking of doing shadow mapping, but the platform I am using is Molehill/Stage3D and it's limited to 8 bits per channel, BGRA textures, and shaders can only read from textures, not depth buffers. I have never done stencil shadows before, but would it be possible to generate a shadow volume entirely on the GPU without the use of Geometry shaders, and only vertex shaders?


texts:
I've been browsing these forums for a while now and I nearly always am able to find an answer without having to ask my own question! Such a great community!

This is the first time I've been stumped so I hope that someone can help me, I'm just learning libgdx so any help is appreciated I know the code is rough but please be gentle as I'm learning everyday!!! :)

I'm trying to create 6 shapes with inputlisteners which eventually will return the index of the shape which will correspond to an answer, but I can only seem to get the last input listener I create to actually fire...

    public Panel(final int count){
    this.count = count;

    img = new Texture("badlogic.jpg");

    handlerShapeVertices = new float[]{128,30,0,256,256,256};
    handlerShape = new Polygon(handlerShapeVertices);

    triangle = new PolygonRegion(new TextureRegion(img), handlerShapeVertices,new short[]{0, 1, 2});

    triangleSprite = new PolygonSprite(triangle);

    triangleSprite.setOrigin(img.getWidth()/2,30);
    triangleSprite.setX(x);
    triangleSprite.setY(y);
    triangleSprite.setRotation(count * 60);

    handlerShape.setOrigin(triangleSprite.getOriginX(), triangleSprite.getOriginY());
    handlerShape.setPosition(x, y);
    handlerShape.rotate(count * 60);

    setBounds(x,y, 256, 256);

    addListener(new InputListener(){
        public boolean touchDown (InputEvent event, float xP, float yP, int pointer, int button) {
            //float [] temp = handlerShape.getTransformedVertices();

            if(resourceManager.getInstance().interSector.isPointInPolygon(handlerShape.getVertices(),0,6,xP,yP)) {
                System.out.println("CLICK INSIDE : " + count);
            }
            return true;
        }
    });

}

I figured the polygon.getTransformedVertices() should work and to check they were correct I drew them in as you can see by the white lines surrounding the polygonsprites however it doesn't seem to and none of the listeners are actually fired when I use that... I'm completely stumped and hope someone has some insight or can point me in the right direction? I don't want someone to write my code for me but a pointer would be greatly appreciated!


texts: How do you add a scripting language to a game?

texts: Let's say I have a game written in C++. But I want to add some modding or scripting functionality to it. How would one go about adding a scripting functionality to your game?


texts:
I believe Uniform Buffers/Blocks has been the hardest thing to grasp in OpenGL. Hopefully this will be my final issue regarding this.

I have created a uniform buffer that contain data of Light objects. Where Light is a structure containing ambient, diffuse, etc. When I have added all my lights with glBufferSubData then I can either call glBindBufferBase to bind the entire buffer to a binding-point, or glBindBufferRangeto bind different Lights to different binding-points.

I can get the latter one to work. For example, If I have added 3 lights, in my program I can do like this to point the uniform-block-array to correct offset in the buffer.

// First parameter: binding-point, second: uniform block name
program->UniformBlockBinding(1, "UBLight[0]");
program->UniformBlockBinding(2, "UBLight[1]");
program->UniformBlockBinding(3, "UBLight[2]");

// Fragment shader code
layout(std140) uniform UBLight
{
    vec3 PositionOrDirection;
    vec3 Diffuse;
    vec3 Specular;
    int Type;
} lights[3];

But what I want to do is just to map the entire uniform buffer to one binding-point, and still be able to use these 3 lights in the shader, that is lights[3]. I've tried to do like this without success:

glBindBufferBase(GL_UNIFORM_BUFFER, 1, id);

program->UniformBlockBinding(1, "UBLight");

It works for the first light, but if I try to use the 2nd or the 3rd light in the shader my model gets black.

Is it possible to solve this in some way, or do I have to bind each Light to a different binding point?

UPDATE #1:

Code showing UniformBlockBinding:

void Program::UniformBlockBinding(GLuint uniformBlockBinding, GLchar *name)
{
    GLuint index = glGetUniformBlockIndex(program, name);

    if (index != GL_INVALID_INDEX)
    {
        glUniformBlockBinding(program, index, uniformBlockBinding);
    }
    else
    {
        printf("Error: the uniform block \"%s\" doesn't exist in program\n", name);
    }
}


texts:
I'm running into a problem where I want to create some code that such that if an object (Cube) is destroyed, it to changes to another scene.

Here is my code:

public class Move : MonoBehaviour {

    void playerWalk()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

        transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.name == "Cube")
            Destroy(col.gameObject);
    }

    void Update ()
    {
        playerWalk();
        if (Input.GetKeyDown(KeyCode.B))
            print("hello");
    }
}

What do do I need to do?


texts: Unity: How to fix collision detection with fast moving objects in 2D?

texts: I was making a simple pong game and it worked fine until I tried to increase speed of the ball. With increased speed ball moves across the walls occasionally. I've set no rigidbody for walls and dynamic rigidbodies for players and the ball. Surely, all of them have colliders. I check collision with OnTriggerEnter2D and all colliders are triggers. How can I solve this problem besides just hard coding collisions?


texts: Fit a bounding box in the scene modifying FOV

texts:
Suppose I have a radius for a spherical bounding box around a mesh.

My goal is to render the scene such as when the camera moves, the bounding box whose centre the camera look at, occupies always more or less the same space. To do so I'm changing the FOV of the camera when it moves, in particular I do:

 FOV = 2 * arctan(radius/distance)

which is the value I feed to  glm::perspective  after the conversion to degrees.

whereas the distance is obtained by

 distance = glm::distance(BBCentre, cameraPosition)

The problem is that when the distance becomes small it is like zooming out the object. For bigger distances, although the object does not occupy the portion of screen I was expecting, it doesn't move.

Am I doing something wrong here?


texts: Does an indie game developer really need to know graphics programming beyond the basics?

texts:
I've been working on a 2D game for the iPhone and learning a lot about game design in the process. I've looked at some of the most popular games for the iPhone ( angry birds, cut the rope, doodle jump, tiny wings, etc..) and have noticed that they're all 2D. Now I understand that some graphics knowledge is needed to create these games, but does a indie game developer really need to know graphics programming beyond the basics?

I feel there are two reasons that 2D games have greater success on mobile. One, lack of controller. Two, casual games need a more casual experience and 2D games cause less visual processing on the brain.

I'm asking this question because I'm still in school getting a cs degree and trying to decide on taking a real-time rendering course that will focus on GLSL and GPU programming or artificial intelligence. I've actually already taken a computer graphics course, but it focused on theory and we touched opengl very little. We implemented the graphics pipeline ourselves.

I get the feeling that studying color theory and basic drawing skills would be more helpful than GLSL or OpenGL ES 2.0 to master the aesthetics part of game design.

I could be short sighted though, because games like Braid and World of Goo might of relied a lot on graphics programming and I would love to be able make games of the same quality of these two.


texts: How to rotate a sprite on circle in android using Libgdx

texts:
Dear Fellow Game Developers
i am newbie to Android Game Development,i like to know how we can develop a sprite rotate in circle on android,with help of libgdx,
i do have a image in assets folder,cant load it in emulator,following code is using to load image in texture

  texture = new Texture(Gdx.files.internal("1325603701_wordpress.png"));


texts:
Does anyone have a good algorithm for generating a random y position for spawning a block, which takes into account a minimum and maximum height, allowing player to to jump on the block.

Blocks will continually be spawned, so the player must always be able to jump onto the next block, bearing in mind the minimum position which would be the ground, and the maximum which would the players jump height bearing in mind the ceiling


texts: How do I make an object's y-axis align with a Vector3?

texts:
I have a golf ball on the ground, and from a raycast, I have the normal which gives me the slope of the ground by the ball.

I have an object which is rendered on the HUD to show that slope to the player.

I have a parent object rotated -90 degrees around X, so that the indicator's Z-axis points up. This way I can do this:

Quaternion yRot = Quaternion.Euler(0, -CameraController.Instance.CachedTransform.eulerAngles.y, 0);
Vector3 displayGroundNormal = yRot * _groundNormal;
_lieIndicator3DParentCachedTransform.rotation = Quaternion.LookRotation(displayGroundNormal);

This, as far as I can tell, takes the ground normal, rotates it around the y-axis so that it shows the proper perspective given the camera's facing. Then it tells that parent object to look in that direction, which aligns its z-axis with the rotated ground normal.

This works, except the object I have also rotates around the y-axis depending on the orientation of the camera. I thought that I was throwing that information away in the second step by keeping only a Vector3 aligned with the ground normal rotated for the camera position.

So I want this:

Not this:


texts: BabylonJS strange behaviour when moving along a diagonal plane

texts:
so I'm trying to create a MOBA style game, this involves point and click movement.

I'm at the point now where i'm messing about with movement:

https://playground.babylonjs.com/#6R8BFY#11

The problem I'm having is that if I click on the ground (so that the mesh moves towards it). If its not perfectly diagonal or straight, then the x axis or the z axis is reached first.

It kind of goes diagonally for a bit before going straight for the rest of the route.

The code is really simple, And my feeling is the movement logic needs improving. I'm essentially applying a force of 1 or -1 depending on where the mesh is currently until it reaches its point as seen below:

/**
* The movement function,
*/
var applyImpulse = function(mesh, destination) {
   var position = mesh.getAbsolutePosition();
   var impulseX = 0;
   var impulseZ = 0;
   if(position.x > destination.x)
   {
     impulseX = -2;
   }
   else
  {
    impulseX = 2;
  }

  if(position.z > destination.z)
  {
     impulseZ = -2;
  }
  else
  {
    impulseZ = 2;
  }
  mesh.lookAt(destination);
  mesh.physicsImpostor.setLinearVelocity(new BABYLON.Vector3(impulseX,0, impulseZ));
}

Using physics means I am pushing it rather than setting, but I bet it would have the same problems even without applying force.

Is there a better way to do this. Like using the ray or something? It kinda sucks.


texts: TypeLoadException when running a Monogame Windows Phone 8 game

texts:
Using Monogame, I'm trying to port a game to Windows Phone 8, but I'm having issues getting a basic example to run.

When I create a basic Mono project and run it on my phone (to check everything's OK), it compiles the game, and deploys it to my phone, but when the app starts running, the debugger throws this error:

I tried adding a reference of that .dll, but that doesn't solve it. This is the first time that I use Monogame, so please bear with me.


texts: How to approach 360 degree snake without having it "slide"

texts:
There's a great question here that helps me a little bit in what I want to do, and it explains it quite well:

How To Approach 360 Degree Snake

Basically, I want to have a smooth 360-degrees Snake game, where the snake follows along. I can easily do the same thing as described in the question above (video example), but as you can see that kind of "drags" or "slides" the snake along, which is not what I'm looking for.

I want the entire snake to follow the entire path that the head of the snake follows.

The only solution I can think of is to make some kind of "buffer" to store the rotations of the head, and then "lag" that behind on the other bodies.

Since I think that will end up way too complex, what's the correct way of implementing it?

Here's a screenshot of how my snake looks like right now, to get an idea of what exactly I want to move:


texts: GLSL 330 Core Bug? - Uniform variable will not set to value if it is named a certain way

texts:
In the code below I have a uniform variable named "vw_matrix" used in the calculation for gl_Position. When I run my program, a rectangle gets printed to the screen.

#version 330 core

layout (location = 0) in vec4 position;

uniform mat4 pr_matrix;
uniform mat4 vw_matrix = mat4(1.0);  // Rectangle!
uniform mat4 m1_matrix = mat4(1.0);  // No rectangle!
uniform mat4 mmmmm = mat4(1.0);      // No rectangle!
uniform mat4 test = mat4(1.0);       // Rectangle!
uniform mat4 aaa = mat4(1.0);        // No rectangle!

void main()
{
    gl_Position = pr_matrix * position * vw_matrix;
}

If instead I put "m1_matrix" in the gl_Position line instead of "vw_matrix". The rectangle no longer appears.  I'm not getting any GLSL compile errors.

void main()
{
    gl_Position = pr_matrix * position * m1_matrix;
}

There are no calls to glUniformMatrix4fv changing the value "m1_matrix".
It has the same value as "vw_matrix" so for some reason it must not be initializing.

I did some experimenting, it won't set a uniform variable if it starts with a certain letter and "m" is one of those letters. Anything that starts with a "v" or "t" works fine. I can't make this up!

Is there anything I should double check/post or is this just a rather bizarre bug? The full code is available at https://github.com/nduplessis11/Freeze

I'm running on Linux Mint 17.1 and my GL_VERSION is "OpenGL 4.4 13374 Compatibility Profile Context 15.20.2013". My video driver is AMD's fglrx version 15.200

UPDATE: Ok, I found a bug in my main program in a function that retrieves the location of a uniform.

GLint Shader::getUniformLocation(const GLchar* name)
{
  // This is a very slow operation, optimize later.
  glGetUniformLocation(m_ShaderID, name);
  return 0;
}

This was causing 0 to be passed as the location for glSetUniform* calls. I'm not sure how, but fixing this function stopped the unpredictable behavior when initializing uniform variables from within the shader program. I'm still going to take Trevor's advice and set them from within my main program.


texts: Ideal 3D platformer controls for Keyboard + Mouse

texts:
I am developing a 3D platformer, and I know that controller is optimal for the precise movement, but I don't feel players should have to buy a controller just to experience a 3D platformer that is available for PC.

I get that WASD to move and SPACEBAR to jump is all good(and SHIFT to crouch), but I'm a little lost for the rest. I was thinking JKL could do some stuff, but then that ruins the point of a mouse, so maybe one set of controls for Keyboard + Mouse, and another for keyboard alone?

Here are my current controls for controller:

Potential Ideas:

Left Stick/WASD - move(obviously)

Right Stick/arrow keys/mouse(maybe + right click?) - camera

A(gamepad)/SPACE(maybe 'j' as well?) - Jump

Triggers/SHIFT - crouch

(No need to worry about start + select)

Ones I'm stuck on(all of these are gamepad)

Right Stick down - first person view

B - Attack

X - Dive

Y - Use power-up

Bumpers - Snap Camera behind

D-Pad Up/Down - zoom camera

D-Pad Left-Right - snap camera 45 degrees to left/right

I tried looking at other examples(e.g. A hat in time), but those games have a much different move set than mine, and wouldn't quite work.


texts:
I'm writing my game on libgdx w/o any of those extensions like box2d and whatsoever. But right now I'm forcing problem with overlapping detection. I need to detect if bullet (which is always in different degree) overlapped my rocket. At first I was using Rectangle, but it sometimes is giving me false overlap.

I have visualized it.

How it is now:

My goal:

as you see I also want to make bullets rectangle rotated so it was more accurate. And as I said earlier I need to detect collision/overlapping between these polygons. Do I need to use that box2d extension??? Because right now I've written working prototype entirely w/o it.


texts:
I built a 2D fighter  yesterday.

The second 'player' does hardly anything. Actually, nothing. To be honest, I have never made a game before that had an opponent like this.

So my question is, how does one start with AI programming for the opponent? Are there any tutorials, any best practices? I want it to be a challenge (for the player, not myself).


texts:
I'm trying to write my own ray tracer. The last days I tried implementing a bounding box algorithm for it. But I'm getting a much slower frame rate with the bounding boxes turned on. I think it has something to do with checking the box with every ray but I don't know how I could change that.
Here is my code for the intersection algorithm:
bool Intersect(Ray r, float3 lb, float3 rt)
{
    float3 dir_inv = 1 / r.direction;

    double t1 = (lb[0] - r.origin[0]) * dir_inv[0];
    double t2 = (rt[0] - r.origin[0]) * dir_inv[0];

    double tmin = min(t1, t2);
    double tmax = max(t1, t2);

    for (int i = 1; i < 3; ++i)
    {
        t1 = (lb[i] - r.origin[i]) * dir_inv[i];
        t2 = (rt[i] - r.origin[i]) * dir_inv[i];

        tmin = max(tmin, min(t1, t2));
        tmax = min(tmax, max(t1, t2));
    }

    return tmax > max(tmin, 0.0);
}

My trace function:
RayHit Trace(Ray ray)
{
    RayHit bestHit = CreateRayHit();
    uint count, stride, i;

    // Trace ground plane
    IntersectGroundPlane(ray, bestHit);

    // Trace spheres
    _Spheres.GetDimensions(count, stride);
    for (i = 0; i < count; i++)
    {
        if (Intersect(ray, _Spheres[i].position - (_Spheres[i].radius), _Spheres[i].position + (_Spheres[i].radius)))
            IntersectSphere(ray, bestHit, _Spheres[i]);
    }

    // Trace mesh objects
    _MeshObjects.GetDimensions(count, stride);
    for (i = 0; i < count; i++)
    {
        //if (Intersect(ray, float3(0.0f, 0.0f, 0.0f), float3(10.0f, 10.0f, 10.0f)))
            //IntersectMeshObject(ray, bestHit, _MeshObjects[i]);
    }

    return bestHit;
}