texts:
I have currently a pygame program that stores tiles in a 2d list like

[[1,1,1]
 [1,1,1]
 [1,1,1]]

where the 1 is a tile object. I have the character centered in the middle of the screen, and I am trying to find the best way to make it so the 'camera' scrolls along with the character. I suppose I could have it so that it only draws the tiles that are in the current window range, but I feel like this will cause problems later. My goal is to have the an entire map, say 100x100 tiles that are drawn but only a small section is shown. So the enemies I generate would still be walking around the map, and things would be going normally except I can only see a small part of it. Is there a way I can take advantage of surfaces in pygame to do this more effectively?

Some relevant code.

def drawMap(self, screen):
    for y in range(self.height):
        for x in range(self.width):
            self._mapData[y][x].draw(screen, x*48,y*48)

This is in the TileMap class and each index is a Tile object, which has a draw method. My initial idea was to change both the range() calls to draw only the area of the map I want to but then I don't know how to account for enemies off the screen because they are defined by their x and y location relative to the TileMap I create.

I am thinking there is maybe something I can do with a larger pygame surface object that I do not realize so I figured I would ask this here.


texts:
We're talking about fairly anal levels of optimisation here that I wouldn't really worry about in anything other than mobile games. Let's say for example you were drawing a texture to the screen in a fairly constant position and the position of that texture could easily be calculated or stored.

I'd be interested to know what professional game developers default to in the first instance when writing code. Which of the two options below would to achieve higher performance in a majority of situations. My main development language is Java.

So option 1 is something like:

constructor {
  x = container.left + offset.x;
  y = container.bottom + offset.y;
}

paint {
  draw(texture, x, y);
}

And option 2 is something like

paint {
  draw(texture, container.left + offset.x, container.bottom + offset.y);
}

With option one the advantage is obviously that the values are pre-calculated. The disadvantages being you're using more RAM and as such there's an increased risk that the data you need wont be in the CPU cache. You also need to make sure the position is recalculated every time there's any movement.

With option two less RAM is used and therefore it's more likely data will be in the CPU cache, but there's the overhead of the calculation. We also don't need to worry about recalculation when there's movement.


texts: .blend scenes are not showing texture in Unity

texts: I am new to Unity and Blender. I am getting a problem when importing .blend files into Unity: in Unity scenes the textures created in Blender are not showing.  But there are no problems with color. How can I fix this problem?


texts: Pipe connection game algorithm - Java/Andengine

texts:
I am creating a game based on Pipe Dream/Pipe Mania using java/andengine for android. I have a square grid of tiles each representing a type of pipe. The player needs to swap tiles to connect the pipes from point A to B.

How do I determine if the pipes are connected to starting point A? How do I then find how far a connected path goes? How do I determine if the path connects point A to point B? How do I handle the switching of tiles which may be in the middle of the path?

This functionality will be almost the same as the pipe mini game in the first Bioshock game.

I am looking for advice on how to go about tackling this problem.


texts:
I'm creating a third-person game. I want the player-model to follow the rotation of the camera. I do that with this :
var camRotation = new Quaternion(cam.rotation.x, cam.rotation.y, cam.rotation.z, cam.rotation.w);
transform.rotation = camRotation;

The horizontal axis works fine, and the model turns with my camera, but the mode vertical axis also tilts up and down, which i do not want.
I've tried zeroing out the rotation.y and z, but this has some strange effects when I do.


texts: Start iTween MoveTo from a specific node? (Unity)

texts:
I just started using iTween as part of my day/night cycle. I'm trying to move the sun and moon along a curve, but I want have the sun/moon start at a specific location depending on the time of day. That would mean beginning the MoveTo() function from, say, the 3rd node instead of the 1st node, but I can't figure out how to access specific nodes.

If that's not possible, is there some other workaround? I thought of making several paths of two nodes each and calling the next path once the first one finishes, but then the object has to move in a series of straight lines.


texts: AddListener will not listen to onClick event

texts:
Based on this question on the Unity forum, I've made this code to instantiate a button and add an onClick event.

// Setting some other component properties right of the prefab.

shopTurretItem.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {
    UnityEngine.Debug.Log("Click");
});

Instantiate(shopTurretItem, transform);

The variabele shopTurretItem is my prefab type of UnityEngine.GameObject.

The problem is that the log Click will never be shown. If I add breakpoints on the first code line, the compiler will stop the code. If I place it into the closure, it'll never be hit if I click on that button.

This is the inspector of my prefab shopTurretItem.

What's wrong with this code?


texts: What data should be cached in a multiplayer server, relative to AI and players?

texts:
In a virtual place, fully network driven, with an arbitrary number of players and an arbitrary number of enemies, what data should be cached in the server memory, in order to optimize smooth AI simulation?

Trying to explain, lets say player A sees player B to E, and enemy A to G. Each of those players, see player A, but not necessarily each other. Same applies to enemies. Think of this question from a topdown perspective please.

In many cases, for example, when a player shoots his gun, the server handles the sound as a radial "signal" that every other entity within reach "hear" and react upon.

Doing these searches all the time for a whole area, containing possibly a lot of unrelated players and enemies, seems to be an issue, when the budget for each AI agent is so small.

Should every entity cache whatever enters and exits from its radius of awareness? Is there a great way to trace the entities close by without flooding the memory with such caches?

What about other AI related problems that may arise, after assuming the previous one works well? We're talking about environments with possibly hundreds of enemies, a swarm.


texts: How can I get separate caches for different coroutines? (Unity)

texts:
I want to fade out an image, so I have a coroutine FadeOut(). However, I want to have a separate image each time I call FadeOut.

If I try to do something like this:

IEnumerator FadeOut(GameObject image) {
    SpriteRenderer render = image.GetComponent<SpriteRenderer>();
    yield return null;
}

Ignoring all the color changing code which I took out, how do I make it so that I can save a separate cache for each image I add? I don't want to run GetComponent() each frame, because I'm running on mobile and because I want to think of a clever way to stash the renderer.

For example, if I declare the renderer at the top like this:

private SpriteRenderer render;

and want to cache it on the first frame of the coroutine, there's the chance that calling FadeOut() on another object will change the renderer to a new object and the first FadeOut() will cancel.

Can I make the method static? Will that cache a private version of renderer?


texts: Best way to load texture2d tiles in xna?

texts:
I am making a test xna game as a learning exercise and I have a small question about using 2d textures. Basically the game is a grid of different 'tiles' which are taken from a text map file. I basically just parse through the file when initializing a level and create a matrix of the different tile types. The level is essentially a tub of wall tiles and spikes. So essentially, there are lots of wall tiles and multiple spike tiles and then lots of empty tiles. However, there are four types of wall tile and spike textures to cover different directions.

My question is what is the best way to load the textures for each of the tile? Do I load individual textures for each tile? i.e when I create a tile, pass it a texture2d which I can draw and load the texture at the same time. This seems like a good way, but then I have to load each tiles texture individually and this seems wasteful.

The other option I can think of is to use a static texture in the tile struct an then simple load this texture as a tile atlas with the different walls and spikes. This way I am only loading a single texture, and then when drawing I just move a rectangle to the area of the appropriate tile within the sprite.

I am not sure which of these ways would be optimal from a performance perspective, or if there is an alternative approach?

Thanks in advanmce


texts: Is there a technique to creating a "black hole" background in XNA?

texts:
I'm creating application in XNA 4.0 and am trying to create a specialized background.
I'm familiar with the creation of a parallax scrolling background but I'd like to create a background image that appears to be draining into a hole.  The issue is that I'd like the drain/black hole to exist in a variable location on the screen so it would be nice to be able to adjust the location of the background.
Is using a background for this even a good idea?  Maybe it'd be easier another way?
Is there a term for this sort of background or is it just a modified version of parallax?
Thanks!


texts:
I have a fairly bog-standard Gaussian blur filter (seperable) I'm using to make a glow effect in my pipeline.  At the moment I'm rendering it only to 256x256 texture and then doing a very simple additive combine with the scene to get the effect.

Due to the low resolution of the blur texture, I get quite a bit of "shimmering" of the blur when the camera moves around.  Actually I noticed this in the Mass Effect 2 game, where they "glow" the specular highlights and shimmering is visible there.

Does anyone know of any technique for reducing or eliminating shimmering/aliasing that doesn't involve rendering the blur to a higher resolution texture (and so killing performance)?  I'm already using GL_LINEAR in my samplers, which helps a bit, but not all that much.

Here's a little YouTube clip of the blur, although it's hard to see after YouTube have downsized and messed around with the clip, unfortunately.

Note that I read this article about real-time glow, and they briefly mention shimmering, but don't go into detail about solutions.

For completeness, I include my blur shader below.

#version 420

// Input uniforms.

uniform vec2 uniform_TexelSize;
uniform float uniform_BlurScale;
uniform float uniform_BlurStrength;
uniform int uniform_Orientation;
uniform int uniform_BlurAmount;

// Shared.

in vec2 attrib_Fragment_Texture;

// Samplers

uniform sampler2D Map_Diffuse;

// Result

out vec4 Out_Colour;

// Local Functions

float Gaussian (float x, float deviation)
{
    return (1.0 / sqrt(2.0 * 3.141592 * deviation)) * exp(-((x * x) / (2.0 * deviation)));
}

// Main

void main(void)
{
    float halfBlur = float(uniform_BlurAmount) * 0.5;
    float deviation = halfBlur * 0.35;

    deviation *= deviation;

    float strength = 1.0 - uniform_BlurStrength;

    vec4 colour = vec4(0.0), texColour = vec4(0.0);

    // Horizontal or vertical?

    if (uniform_Orientation == 0)
    {
    // Horizontal.

        for (int i = 0; i < 10; ++i)
        {
            if (i >= uniform_BlurAmount)
                break;

            float offset = float(i) - halfBlur;

            texColour = texture2D(Map_Diffuse, attrib_Fragment_Texture + vec2(offset * uniform_TexelSize.x * uniform_BlurScale, 0.0)) * Gaussian(offset * strength, deviation);

            colour += texColour;
        }
    }
    else
    {
        // Vertical.

        for (int i = 0; i < 10; ++i)
        {
            if (i >= uniform_BlurAmount)
                break;

            float offset = float(i) - halfBlur;

            texColour = texture2D(Map_Diffuse, attrib_Fragment_Texture + vec2(0.0, offset * uniform_TexelSize.y * uniform_BlurScale)) * Gaussian(offset * strength, deviation);

            colour += texColour;
        }
    }

    Out_Colour = colour;
}


texts: Are there alternatives to multiple buffering?

texts:
I'm learning about game programming. So far, my sources lead me to believe that multiple buffering is the best technique for redrawing in OpenGL.

Are there other redrawing techniques? What are their advantages/disadvantages?

I'm not sure about terminology yet, but googling as best as I can hasn't yielded much result yet. Does anyone have any experience with redrawing techniques besides multiple buffering?


texts: Unreal Engine 4: Help with multithreading and accessing render target images

texts:
I am working on an application where I need to record images seen from an in-game camera. Initially, the method was to set up a TextureRenderTargetResource from the in-game capture component, and subsequently call ReadPixels to access the frame data and save that data as an image. (code flow below)

bool saveImage() {
  USceneCaptureComponent2D* capture = getCaptureComponent(camera_type, true);
  FTextureRenderTargetResource* RenderResource = capture->TextureTarget->GameThread_GetRenderTargetResource();
  width = capture->TextureTarget->GetSurfaceWidth();
  height = capture->TextureTarget->GetSurfaceHeight();

  TArray<FColor> imageColor;
  imageColor.AddUninitialized(width * height);
  RenderResource->ReadPixels(bmp);
}

This approach was slowing the game thread down significantly, so I am trying to move the screenshot saving procedure to its own thread. My approach now is inspired by the article at https://wiki.unrealengine.com/Multi-Threading:_How_to_Create_Threads_in_UE4. I access the *AActor object from this separate thread and subsequently its camera, and then I call the saveImage() function from the thread: but this is resulting in a crash with no additional information (just "UE4Editor.exe has triggered an exception") at the call to ReadPixels(). So essentially, calling saveImage() and thereby ReadPixels() from the game thread works perfectly, and it fails when I call it from a different thread. Am I doing something wrong in my process here?


texts: Why aren't regular quadratic and cubic splines used much in games?

texts:
After investigating a bit about splines and reading a bunch of docs, I have noticed regular quadratic and cubic splines are not used very much in games.

Splines using quadratic/cubic Bézier curves, Catmull-Rom, B-splines, and other spline interpolation methods seem to be used widely though.

I can be totally wrong here but from books and tutorials I have seen that for regular cubic/quadratic you have to solve systems including first derivative for continuity and second derivative to match curvature. It seems that the most used splines (Bézier, Catmull-Rom, etc...) implicitly bring these features with fewer calculations.

Is this the reason that regular quadratic and cubic spline interpolation are not often used in game programming?


texts: Prefabs moved to before position when zooming scene

texts:
I have build some pipes for waterline drawing, like following screencast:
https://youtu.be/WnJb1JwOW78
As you can see, when I zoom in the scene,  Pipes moved to lower position. When i zoom out, Pipes moved to higher position.
Actually I have changed the position and  moved down the pipe position before, the unexpected higher position was the pipe before position.
So i guessing this problem might about cache clean.
So I I try to clear the GI cache, but the problem still exist.
And then I try to build a windows executable file and run game again, problem still.
How to fix it?
I am using  Unity 2018.4


texts: Organizing Setup(), Update() and Draw() function in a game engine

texts:
I'm creating my first game engine and I want help with organizing the Setup(), Update() and Draw() functions in the correct way.

Here is how my main() function looks like

/* BEGIN main() Function */
int main(int argc, char *argv[])
{
    prepareSetting(&settings);

    initEngine();

    setup();

    // Main loop

    while (!done)
    {
        update();
        draw();
    }

    SDL_Quit();
    return 0;
} /* END main()*/

The above approach requires me to declare the shared variables as global, which I think is not a good thing to do.

I was thinking about creating a ENGINE class which contains the setup(), update() and draw() functions and inheriting it. libcinder use this kind of approach.
So should I use classes or leave them as it is. What is the best way to organize those functions?

What approach is used by professionals in the industry?


texts: Repeating Sound with Timer in Actionscript 3

texts:
I'm working on a Flash game and am trying to figure out how to repeat a sound periodically every 17 seconds. Instead, of having the sound repeat once the .mp3, .wav, finishes.

The problem I'm running into is the sound is repeating itself after the song finishes, and the timer isn't doing anything. I put the timer in the initTitle area because I'm working on my main menu, and then I initialize the sound, and read if the sound finishes.
How can I get it so that sound repeats every 17 seconds?

    public function initTitle():void
    {
        initSoundThemeSong();
        initTitleWhooshSound();

        drawTitleBG();
        drawTitleLogo();
        drawTitleBGStars();
        drawTitleStart();

        titleWhooshTimer = new Timer ( 17000 );
        titleWhooshTimer.addEventListener( TimerEvent.TIMER, onTitleWhooshFinished );
        titleTimer.start();
    }

    public function initTitleWhooshSound():void
    {
        titleWhoosh = new TitleSoundWhoosh();
        titleWhooshSoundChannel = titleWhoosh.play();
        titleWhooshSoundChannel.addEventListener( Event.SOUND_COMPLETE,
                                                  onTitleWhooshFinished );
    }

    public function onTitleWhooshFinished( event:Event ):void
    {
        titleWhooshSoundChannel = titleWhoosh.play();
        titleWhooshSoundChannel.addEventListener( Event.SOUND_COMPLETE,
                                                  onTitleWhooshFinished );
    }

Thanks! :)


texts:
I'm interested in creating a world in which the behaviors of some of the elements are generated randomly or evolved. Is there a field of study or some well known work that deals with what it takes to create a stable ecosystem?

For instance, let's say I randomly generate three creatures that each eat each other. It's easy to imagine that one of the creatures might be dramatically better than the other two, kill all of its prey and defend itself against all of its predators. This will result in everything in the world dying, which isn't very interesting.

I'm looking for techniques which help to find or guarantee ecosystems that don't implode or explode, but instead oscillate within some interesting (hopefully fun!) bounds.


texts: How to implement Boids steering efficiently? (ie. find nearest neighbours of moving entities)

texts:
As I understand it, modern pathfinding uses ideas such as Boids steering on top of traditional A* and Dijkstra's algorithm.

It's easy to find recommendations for implementing Dijkstra's algorithm efficiently in say C++. That is I can find out what are the typical data structures to use.

With Boids steering I cannot find anything that definitively says what is the recommended way to go. You have these moving units and you need to be able to find for each unit all the nearby units to apply steering or whatever else.

What kind of data structure can I use to perform these nearest neighbour queries efficiently?


texts: Inverted left & right stick axes in SDL2

texts:
I've faced a weird problem with SDL2.

case SDL_CONTROLLERAXISMOTION:
    switch (e->caxis.axis)
    {
    /* LEFT && RIGHT Stick Movement */
    case SDL_CONTROLLER_AXIS_LEFTY:
        puts("Y");
        break;
    /* UP && DOWN Stick Movement */
    case SDL_CONTROLLER_AXIS_LEFTX:
        puts("X");
        break;
    }
    break;

Using my Xbox 360 Controller on Windows 10, I just the move the left stick forward and backward which is in the y-axis logically. But it prints X instead.

There's no problem with my controller since it works as it should be with all other games.

I've also used some gamepad tools for debugging and the results are the true y and x axes directions.

What did I miss? It's the same with the right stick too.


texts: Interact with texture / flat surface (Unity)

texts:
I don't know exactly how to put this into words, so googling did nothing really for me.

Imagine a bowling game. On the oldern bowling lanes there was only a scheme of the pins above the lane, lighting up all the pins that are still standing, while the ones that already fell, were not lit anymore.

How can I achieve this in Unity? Is there any way to do this, without having to make something stupid like creating hundreds of textures, with all the possible combinations and swap them out?

I'm still very new to Unity, so I'd love to know the best approach to something like this.

Thank you very much in advance


texts:
I need to be able to control the speed in which the gun fires.
I'm trying to use the couroutine to limit the speed of update method but it doesn't work for some reason.

I've tried several fireRate values(10K etc.), none of them seem to slow the updates. How can I accomplish this feat?

 float fireRate = 10.1f;

        public IEnumerator CheckFireRate()
        {
            yield return new WaitForSeconds(fireRate);
        }

        void Update()
        {
            StartCoroutine(CheckFireRate());
            //Fire gun
        }


texts:
I found an underwater (distort) effect and I got it to work but somehow I cannot make it animate given the offset here:

Fragment Shader code:

uniform sampler2D fbo_texture;
uniform float offset;
varying vec2 f_texcoord;

void main(void) {
  vec2 texcoord = f_texcoord;
  texcoord.x += sin(texcoord.y * 4*2*3.14159 + offset) / 100;
  gl_FragColor = texture2D(fbo_texture, texcoord);
}

Original Source here


texts: Movement-networking for a Worms-like game

texts:
I want to implement a strategy/artillery game, similar to Worms/Arcanists.

As game-development (and game-networking especially) is new to me, I was wondering whether this would be a good/performant way to do the movement-networking:

Server has all client's positions.
Moving-client to server:

Message: [start-moving, moving-direction]
Server now starts a simulation of the moving-client moving.
Server to all clients, except originating one, every 100ms(?):

Message: [set-client-position: client-id, new-position]
^ new-position calculated by the server's simulation
Clients lerp the moving-client's position.
Moving-client to server:

Message: [stop-moving]
^ server's simulation ends
Server to all clients, including originating one:

Message: [set-client-position: client-id, final-position]
^ all clients have the same position for the moving-client in the end


texts: I have points X,Y,Z and have a camera at Cx,Cy,Cz. Assuming the camera is not rotated and is facing the -Z direction and is at 0,0,0. What would the math be for projecting the X,Y,and Z values onto the 2d projection plane that is at a distance of znear from the camera. This is also assuming that X,Y,and Z will be in the camera's view.


texts: Create a body of an irregular 2D sprite in Farseer

texts:
I'm trying to create a body of a irregular 2D sprite Farseer 3.3.1.
The regular shapes that BodyFactory provides are not that I want. Is there a way that one can create irregular objects? Could it be done using the BodyFactory.CreateCompoundPolygon method?


texts: Tetris style game in java (for now) will I need to use threads?

texts:
I'm looking at developing a puzzle game, it might be like tetris or something similar, perhaps more like bejewelled in that the player will select objects with the mouse to manipulate them.

I've been studying java part-time in college for the past year, really beginner stuff, but I've decided to build a game over the summer to keep the brain active :-D

So far I've animated some primitive shapes moving around the screen using the timer from the utilities package. This is all good, they're behaving the way I want.
So now I've decided to try manipulate the shapes with the mouse. Just some really simple stuff, maybe change the colour of an object when I click on it.

To test the mouse functions I've successfully completed the MouseEvent and MouseListener tutorials on The New Boston.
However, I can't get these events working in my code. I suspect I'm going to have to re-write my classes.

Will I need separate threads within the game, for example, one thread to animate the objects and another to listen for and handle mouse events.

My understanding is that I should implement runnable on my classes when using threads in Java games.
Am I thinking on the right lines?


texts: Implementing online connectivity and multiplayer/PVP for a newbie

texts:
Background

I'm a noob programmer looking to create a simple turn based mobile game as a side project. I've pretty much got the game logic down and am left with implementing the online multiplayer/PVP portion.

More specifically, i'm looking to implementing a system when the player clicks play and will be matched with an opponent in a 1 v 1 format, without any lobbies etc etc.

I'm currently trying to develop my game in android studio(i'm new) but am also open to unity if it makes the development easier.(I have no experience in Unity).

What i want to know

From what i understand,i need to create and host my own server for the multiplayer to run(i.e matching of player to opponent). Do i also need the server to run the game itself or am i able to connect the player to the opponent and simply record the result of the game to my server/database?

Also, how would i go about creating and running/hosting the server? I heard nodeJS is a good choice for writing the server.

End Goal

I just wanna publish my game onto the app store, IOS store, etc.


texts:
I am not able to draw only one HUD of my game on a separate canvas, so I do not have to redraw it to each frame, I have four functions, init(), render(), loop() and drawHUD():

init() is my function that I call when starting the game, right at the end of the script.

render() is my rendering function

loop() is my game loop function (do not notice it, I've simplified it with minimal to leave the code cleaner for reading)

drawHUD() is my function to draw HUD on Canvas HUD_CANVAS

The problem is that the code below does not work, the screen remains blank, but if I put drawHUD() inside the render() before CTX.drawImage (HUD_CANVAS, 0, 0); then it works and I can see the image on the screen, however I wish I could draw only once, not every frame, since my HUD will not always be updating.

What am I doing wrong?

  index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>

    <style type="text/css" media="screen">
        canvas {
            padding: 0;
            margin: auto;
            display: block;
            width: 640px;
            height: 480px;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            border: 1px solid #999;
        }
    </style>

</head>

<body>

    <canvas id="canvas" style="z-index: 0;" width="640" height="480"></canvas>
    <canvas id="hud-canvas" style="z-index: 1;" width="640" height="480"></canvas>

    <script>
    const CANVAS = document.getElementById('canvas');
    const CTX = CANVAS.getContext('2d');
    const HUD_CANVAS = document.getElementById('hud-canvas');
    const HUD_CTX = HUD_CANVAS.getContext('2d');

    function drawHUD() {
        const imgHUD = new Image();
        imgHUD.src = './hand_hud_maya.png';
        HUD_CTX.drawImage(imgHUD, 0, 0, 96, 96, 0, 0, 96, 96);
    }

    function init() {
        drawHUD();
        loop();
    }

    function render() {
        CTX.drawImage(HUD_CANVAS, 0, 0);
    }

    function loop() {
        render();
        requestAnimationFrame(loop);
    }

    init();

    </script>

</body>
</html>

Example:

https://jsfiddle.net/twkq0sn6/

  Up1:

Change that part of the function, I can see the red rectangle on the screen, so I think the problem is with the drawImage() function, but I do not know what it can be, I already tested several images, I do not think it's the image.

 function drawHUD() {
     HUD_CTX.fillStyle = "red";
     HUD_CTX.fillRect(50, 50, 50, 50);
 }

the image is loaded properly, I can see in the chrome network tab the preview of it, all OK. I do not get any errors, it's hard to figure out where I'm going wrong.


texts: How can I set the attribute index location?

texts:
I am trying to set up a shader which takes three input parameters. I have the following code:

GLuint vert = glCreateShader(GL_VERTEX_SHADER);
GLuint frag = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar* vertsrc = src.vertex.c_str();
const GLchar* fragsrc = src.fragment.c_str();
glShaderSource(vert, 1, &vertsrc, NULL);
glShaderSource(frag, 1, &fragsrc, NULL);
glCompileShader(vert);
glCompileShader(frag);
GLuint program = glCreateProgram();
glAttachShader(program, vert);
glAttachShader(program, frag);

glBindAttribLocation(program, 0, "position");
if (glGetError() != GL_NO_ERROR) ...
glBindAttribLocation(program, 1, "normal");
if (glGetError() != GL_NO_ERROR) ...
glBindAttribLocation(program, 2, "texcoord");
if (glGetError() != GL_NO_ERROR) ...

glLinkProgram(program);
//...check linking errors

auto p = glGetAttribLocation(program, "position");
auto n = glGetAttribLocation(program, "normal");
auto t = glGetAttribLocation(program, "texcoord");

GL_MAX_VERTEX_ATTRIBS is 16. I don't understand why, after this code executes, the values I get from glGetAttribLocation are as follows:

p = 0
n = -1
t = -1

Needless to say, I am unable to pass anything beyond vertex attrib array no. 0 to my shader. What am I doing wrong?


texts:
I am struggling with implementing a proper Framebuffer Object .

glCheckFramebufferStatus is returning me:
 GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT (36054).

What am i missing?

GLuint fbo, rboColor, rboDepth;

// Color renderbuffer.
glGenRenderbuffers(1,&rboColor);
glBindRenderbuffer(GL_RENDERBUFFER,rboColor);
// Set storage for currently bound renderbuffer.
glRenderbufferStorage(GL_RENDERBUFFER, GL_BGRA, _w, _h);

// Depth renderbuffer
glGenRenderbuffers(1,&rboDepth);
glBindRenderbuffer(GL_RENDERBUFFER,rboDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, _w, _h);

// Framebuffer
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER,fbo);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,     GL_RENDERBUFFER, rboColor);
// Set renderbuffers for currently bound framebuffer
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,rboDepth);

 // Set to write to the framebuffer.
glBindFramebuffer(GL_FRAMEBUFFER,fbo);

// Tell glReadPixels where to read from.
glReadBuffer(GL_COLOR_ATTACHMENT0);

GLenum e = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);//glCheckFramebufferStatus: check the completeness status of a framebuffer
if (e != GL_FRAMEBUFFER_COMPLETE) {
printf("\nThere is a problem with the FBO.");

}


texts: player moving continuously from button controls

texts:
I added new buttons in my game made with unity 5.0 and the new UI feature.

The player keeps on moving when button is clicked instead of moving just once.

In the normal controls I make it move only once by changing back the x and y of movement to 0.

moving.x = moving.y = 0;

But how will I do that for button function?

I am calling each left, right, up, down , gun function separately in each button:

using UnityEngine;
using System.Collections;

public class UI : MonoBehaviour {

    public Vector2 moving = new Vector2();
    public int Bulletlimit = 0;
    public int MaxBulletlimit = 3;
    public bool Gun;
    private float lastShotTime ;
    public float fireDelay = 0.2f;
    public Transform BulletDirection;

    public Bullet bullet;

    // Use this for initialization
    void Start () {
        lastShotTime = Time.time;
    }

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

        moving.x = moving.y = 0;
        if (Input.GetKey ("right")) {
            right ();
        } else if (Input.GetKey ("left")) {
            left ();
        }

        if (Input.GetKey ("up")) {
            up();
        } else if (Input.GetKey ("down")) {
            down ();
        }

        if (Input.GetKey ("s")) {
            gun ();
        }

    }

    public void BulletCount()
    {
        Bulletlimit = Bulletlimit - 1;
    }

    public void left()
    {
        moving.x = -1;
    }

    public void right()
    {
        moving.x = 1;
    }

    public void up()
    {
        moving.y = 1;
    }

    public void down()
    {
        moving.y = -1;
    }

    public void gun()
    {
        if(Gun){
            if(Bulletlimit < MaxBulletlimit)
            {
                if(Time.time > lastShotTime + fireDelay)
                {
                    Bullet clone = Instantiate (bullet, BulletDirection.position, Quaternion.identity) as Bullet;
                    Bulletlimit = Bulletlimit + 1;
                    lastShotTime = Time.time;
                }
            }
        }

    }

}


texts: Why do I get this error when converting an XNA .fx to a MonoGame .fx?

texts:
I am learning game development in Monogame via book for XNA 4.0. In the code below which is for drawing the terrain, I get the error in the comment.
Im using an effect from Monogame content pipeline folder, and I noticed that there are some differences between the effect file described in the book and the pipeline generated effect. how do i convert the syntax of XNA to Monogame?

    public void Draw(ArcBallCamera camera, Effect effect)
    {
        effect.CurrentTechnique = effect.Techniques["BasicColorDrawing"];
        effect.Parameters["WorldViewProjection"].SetValue(Matrix.Identity * camera.View * camera.Projection);
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            device.SetVertexBuffer(vertexBuffer);
            device.Indices = indexBuffer;
            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexCount);
            //ERROR: An error occurred while preparing to
            //draw. This is probably because the current vertex declaration
            //does not include all the elements required by the current
            //vertex shader. The current vertex declaration includes these
            //elements: SV_Position0, NORMAL0, TEXCOORD0.

        }
    }

the effect file:

#if OPENGL
#define SV_POSITION POSITION
#define VS_SHADERMODEL vs_3_0
#define PS_SHADERMODEL ps_3_0
#else
#define VS_SHADERMODEL vs_4_0_level_9_1
#define PS_SHADERMODEL ps_4_0_level_9_1
#endif

matrix WorldViewProjection;

struct VertexShaderInput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
};

struct VertexShaderOutput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
};

VertexShaderOutput MainVS(in VertexShaderInput input)
{
VertexShaderOutput output = (VertexShaderOutput)0;

output.Position = mul(input.Position, WorldViewProjection);
output.Color = input.Color;

return output;
}

float4 MainPS(VertexShaderOutput input) : COLOR
{
return input.Color;
}

technique BasicColorDrawing
{
pass P0
{
    VertexShader = compile VS_SHADERMODEL MainVS();
    PixelShader = compile PS_SHADERMODEL MainPS();
}
};

the book is "XNA 4 3D Game Development by Example Beginners Guide" BY Kurt Jaegers, published in 2012


texts: How do I convert OnCollisionEnter2D to OnMouseDown?

texts:
I created a simple animation.

I have a "Gamer" object, which I move and hit squares to destroy them.

Squares I have to destroy in the right order (1-2-3-4-5 etc.)

If I make a mistake, the animation comes to an end.

However, I would like to change this code now. I would like to change OnCollisionEnter2D() on OnMouseDown().

I would like to continue to delete the squares one by one, but instead of using a collision - simply click on the squares.

Could anyone help you convert this code?

This is my code posted to the "Gamer" object:

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

    public class Gamer : MonoBehaviour {

    int index =1;
    public GameObject gameOverText, restartButton ;

    public GameObject WinningText, ExitButton, NextLevelButton ;

    public GameObject Manager;

    void Start () {
        gameOverText.SetActive (false);
        restartButton.SetActive (false);
        Manager.SetActive (true);
        WinningText.SetActive (false);
        ExitButton.SetActive (false);
        NextLevelButton.SetActive (false);
    }
    public void OnCollisionEnter2D (Collision2D col)
    {
        Debug.Log("Player hit object: " + col.transform.name);
        //check if the object you hit is one of the "collisionObjects":
        if(col.transform.GetComponent<collisionObject>())
            GetComponent<AudioSource>().Play();
        {
            collisionObject colObj = col.transform.GetComponent<collisionObject>();
            if(!colObj) return;
            if(index == colObj.myIndexNumber) {
                if (colObj.isHighestNumber) {
                    Debug.Log ("Yay you correctly hit the last Square, You WIN!");
                    WinningText.SetActive (true);
                    NextLevelButton.SetActive (true);
                    ExitButton.SetActive (true);
                    gameObject.SetActive (false);
                    Manager.SetActive (false);
                }
                Destroy(col.gameObject);
                index++;

            }
            // here, we know it didn't match the number. :)
            else  {
                gameOverText.SetActive (true);
                restartButton.SetActive (true);
                gameObject.SetActive (false);
                Manager.SetActive (false);

            }
        }
    }
}

And this is my code placed in the "square" object:

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

        public class collisionObject : MonoBehaviour {
           public int myIndexNumber;
           public bool isHighestNumber;
           public void Start()
           {

        isHighestNumber = true;
        //find all other objects:
        foreach (collisionObject cObj in GameObject.FindObjectsOfType<collisionObject>()) {

            //check if any of the other objects has a larger number than mine, if yes, note to self that i am not the highest number.
            if (cObj.myIndexNumber > myIndexNumber) {
                isHighestNumber = false;
                break;
            }
        }
        Debug.Log("Object number " + myIndexNumber + " is here // is highest Number: " + isHighestNumber);
    }
}


texts: unsmooth blending with deferred shading and light volumes

texts:
So I implemented deferred Shading with a single full screen light pass (picture 2) (by passing the light-data as an array to the shader) and deferred shading with point light volumes (picture 1) (by rendering the back faces of spheres with the radius of the light). To "add" the color of two separate lights i used blending
glCullFace(GL_FRONT);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);

(while in the single light pass i just added the light values to the rgb color)

Else both light calculations are the same.
Yet i get those weird "lines" where one pixel is being lit by more than one light source, whereas the single pass results in a smooth transition.
I guess the problem is the blending equation, but i can't find a solution.
The resulting color of the light volume shader looks like this
//d is the normal/light direction equation
//sp is the specular value
//att is the attenuation
//diff is the material color
color = vec4(diff * light_color * (d + sp) * att, 0.0);

The described values should be right.


texts:
I want to implement a system where the player can draw runes on the screen with multiple gestures. Meaning its not just one motion it can be up to 3. So far I have implemented the $P Recognizer . In the example it works great and is exactly what I want. But its made with .Net 4.0 and the dll does not work with unity. I eventually managed to get it working by compiling down to 3.5. The problem is that  the integration in unity does not work well at all. It recognizes the shape but when I draw wrong symbols it recognizes them as well. I'm completely lost as how to proceed fixing this. Here is my code that handles the integration.

if (Input.GetMouseButtonDown(0))
        {
            clone = Instantiate(trailHolderPrefab, transform.position, Quaternion.identity) as GameObject;
            clone.transform.SetParent(transform);
            i++;
        }
        if (Input.GetMouseButton(0))
        {

            points.Add(new Point(Input.mousePosition.x, Input.mousePosition.y, i));

            Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
            Vector3 pos = r.GetPoint(_distance);
            transform.position = pos;
        }
        if(Input.GetMouseButtonUp(0))
        {

            if(i>=3)
            {
                i = 0;
                Point[] _points = points.ToArray();
                Gesture candidate = new Gesture(_points);
                string gestureCLass = PointCloudRecognizer.Classify(candidate, trainingSet);
                spellname.text = gestureCLass;
            }
            clone.transform.parent = null;
            clone.GetComponent<TrailRenderer>().autodestruct = true;

          // GestureXML.GestureIO.WriteGesture(_points, "Triangle",Application.persistentDataPath+"test"+i.ToString()+".xml");
        }


texts: LWJGL Rendering a 2D Object at a Certain Position On-Screen

texts: Okay, so in LWJGL, how can I render a 2D object (maybe for like a menu, or meter that shows up on screen during the game), and have control over size and position on screen? So I can tell it what position relative to the screen. It is a 3d game using gluPerspective (as opposed to glOrtho).


texts: What is the best way to display a cut scene?

texts:
How do we show cutscene in the game? Currently I am using images and animation upon them to show cutscenes or story. I heard from my friend that showing a video might be one of the option too.
Is it a good option or is there any other option except those two? I'd also like to know pros and cons of each option if you can provide.


texts:
My sister is working on a visual novel. We wanted to use unity to build it. She wants to have videos with clickable buttons to skip to other scenes. The problem is we both are noobs! Do you guys have any tips on tutorials or anybody knows if this is possible? What would be the best method to tackle this.

I figured having each scene as an mp4 and having buttons trigger each mp4. but, how would that work with time-triggered Audio?


texts: How to add ingame tutorial for first time?

texts:
I want to know how to show tutorial when player playing for First time.
Only once


texts: How to change object details based on zoom

texts:
I have created the map of a huge terrain (10,000 x 12,000) vertices, which results in about 240 million triangles. Loading all these is very heavy and slows down the scene significantly. To make it more efficient, I am thinking of using a fraction of the vertices when the camera is away (say one for every 10 vertices) and as the camera zooms in on the map, I would increase the number of vertices.

The problem is, even when the camera is zoomed in and a small fraction of the map is viewed at full resolution, the scene is still loading very slowly because of all the drawings that are happening outside the viewport.

My question is, how do I calculate which vertices are in the viewport so that I don't draw them. Or, alternatively, is there a better way of handling increasing the resolution as I zoom in (note that I am not using textures)


texts: How are non-repetitive pixel backgrounds created in 2D games? (e.g., Superbrothers: Sword & Sworcery EP)

texts:
What methods are used to create complex, rich, non-repetitive 2D pixel backgrounds in games like Superbrothers: Sword & Sworcery EP? Examining screenshots from the game, I really can't detect tiles anywhere; there's seemingly no repetition:

Are backgrounds like that simply created as large one-of-a-kind images, or are the developers just being extremely clever about their use of repeated sprites and tiles?

Sub-question: I understand that tiles were very important in decades past because of RAM limitations, but is it reasonable to assume that today's games could simply use a single large background image instead? Even on an iOS game like S:S&S EP?


texts: Per-vertex position/normal and per-index texture coordinate

texts:
In my game, I have a mesh with a vertex buffer and index buffer up and running.  The vertex buffer stores a Vector3 for the position and a Vector2 for the UV coordinate for each vertex.  The index buffer is a list of ushorts.  It works well, but I want to be able to use 3 discrete texture coordinates per triangle.

I assume I have to create another vertex buffer, but how do I even use it?

Here is my vertex/index buffer creation code:

// vertices is a Vertex[]
// indices is a ushort[]
// VertexDefs stores the vertex size (sizeof(float) * 5)

// vertex data
numVertices = vertices.Length;
DataStream data = new DataStream(VertexDefs.size * numVertices, true, true);
data.WriteRange<Vertex>(vertices);
data.Position = 0;

// vertex buffer parameters
BufferDescription vbDesc = new BufferDescription()
{
    BindFlags = BindFlags.VertexBuffer,
    CpuAccessFlags = CpuAccessFlags.None,
    OptionFlags = ResourceOptionFlags.None,
    SizeInBytes = VertexDefs.size * numVertices,
    StructureByteStride = VertexDefs.size,
    Usage = ResourceUsage.Default
};

// create vertex buffer
vertexBuffer = new Buffer(Graphics.device, data, vbDesc);
vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexDefs.size, 0);
data.Dispose();

// index data
numIndices = indices.Length;
data = new DataStream(sizeof(ushort) * numIndices, true, true);
data.WriteRange<ushort>(indices);
data.Position = 0;

// index buffer parameters
BufferDescription ibDesc = new BufferDescription()
{
    BindFlags = BindFlags.IndexBuffer,
    CpuAccessFlags = CpuAccessFlags.None,
    OptionFlags = ResourceOptionFlags.None,
    SizeInBytes = sizeof(ushort) * numIndices,
    StructureByteStride = sizeof(ushort),
    Usage = ResourceUsage.Default
};

// create index buffer
indexBuffer = new Buffer(Graphics.device, data, ibDesc);
data.Dispose();

Engine.Log(MessageType.Success, string.Format("Mesh created with {0} vertices and {1} indices", numVertices, numIndices));

And my drawing code:

// ShaderEffect, ShaderTechnique, and ShaderPass all store effect data
// e is of type ShaderEffect

// get the technique
ShaderTechnique t;
if(!e.techniques.TryGetValue(techniqueName, out t))
    return;

// effect variables
e.SetMatrix("worldView", worldView);
e.SetMatrix("projection", projection);
e.SetResource("diffuseMap", texture);
e.SetSampler("textureSampler", sampler);

// set per-mesh/technique settings
Graphics.context.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
Graphics.context.InputAssembler.SetIndexBuffer(indexBuffer, SlimDX.DXGI.Format.R16_UInt, 0);
Graphics.context.PixelShader.SetSampler(sampler, 0);

// render for each pass
foreach(ShaderPass p in t.passes)
{
    Graphics.context.InputAssembler.InputLayout = p.layout;
    p.pass.Apply(Graphics.context);
    Graphics.context.DrawIndexed(numIndices, 0, 0);
}

How can I do this?


texts: How should I store levels in a C++ game?

texts:
I am writing in C++. I am storing game levels as a 2-dimensional int array. This may be a hacky way of doing things, but I am not ready to change it unless I have to. I store values in the array and then draw them as I read the array. These are constant for me but I need to access them from multiple files.

How can I do this? If I put the level arrays in a header (.h) file and include it in many places I get a redefined variable compilation error. Is there a way to define a variable so it can't be used more than once?

How can I go about this in a better way?


texts: is this approach correct to make my game framerate indipendent in javascript?

texts:
this is what i did

my game loop is run every REFRESH milliseconds

loop = setInterval(tick,REFRESH);

in the loop i calculate how much time is passed since last tick and subdivide that for how much time i expected to be passed

var now = performance.now();
var elapsedTime = now - lastTick;
var delta = time / REFRESH;
lastTick = now;

and every time based action that should happen every tick is "scaled" with the delta factor,
for example my movement code

var distance=ball.dest.x-ball.x;
var movement=distance/speed;
ball.x+=movement;

will have movement multiplied with delta


texts: Zero vector test in projection intersection test in SAT

texts:
I stumbled across this implementation for a projection intersection test to use in a SAT test:

// aCorn and bCorn are arrays containing all corners (vertices) of the two OBBs
private static bool IntersectsWhenProjected( Vector3[] aCorn, Vector3[] bCorn, Vector3 axis ) {

    // Handles the cross product = {0,0,0} case
    if( axis == Vector3.zero )
        return true;

    float aMin = float.MaxValue;
    float aMax = float.MinValue;
    float bMin = float.MaxValue;
    float bMax = float.MinValue;

    // Define two intervals, a and b. Calculate their min and max values
    for( int i = 0; i < 8; i++ ) {
        float aDist = Vector3.Dot( aCorn[i], axis );
        aMin = ( aDist < aMin ) ? aDist : aMin;
        aMax = ( aDist > aMax ) ? aDist : aMax;
        float bDist = Vector3.Dot( bCorn[i], axis );
        bMin = ( bDist < bMin ) ? bDist : bMin;
        bMax = ( bDist > bMax ) ? bDist : bMax;
    }

    // One-dimensional intersection test between a and b
    float longSpan = Mathf.Max( aMax, bMax ) - Mathf.Min( aMin, bMin );
    float sumSpan = aMax - aMin + bMax - bMin;
    return longSpan < sumSpan; // Change this to <= if you want the case were they are touching but not overlapping, to count as an intersection
}

I now don't really get why there is a check for the zero vector, i.e. these lines right here:

if( axis == Vector3.zero )
    return true;

Why can we immediately say that the projections intersect, when there is a zero vector as projection axis?

The code is from Acegikmo answer on this question right here: How many and which axes to use for 3D OBB collision with SAT

He just states, that:

  The cross product will give you a zero vector {0,0,0} when any two
  axes between the objects point in the same direction.

Can anyone clarify this?


texts: Is there a way to normalize for both ways in Unity?

texts: I have a building, built in blender, that has been imported to Unity. And I flipped every necessary piece and calculated the normals inside in blender. However, since I made the rooms inside the building with just a single cube, it's only visible from one side like they're not visible until I go the way around. Is there a way to solve this?


texts:
How can I compute the eight corners of a cuboid given a Depth and Height and two points: A(x,y,z) and B(x,y,z)?

Is it possible to calculate the eight corners/points of a cuboid given only a limited data? I'm trying to make a cuboid with only two 3D vectors by computing the eight vectors.


texts:
I want to implement a heightmap-based water simulation algorithm in Unity. I know exactly how I would approach this in pure low-level C++ and OpenGL (and also Shadertoy), and most of it is straightforward to port to Unity.
The algorithm needs terrain height information with a heightmap. I'd like it to be flexible, so I don't want to force the user to use a terrain heightmap that has to exactly fit the area where the water is supposed to go. Instead, I'd like the user to model terrain and other static geometry in any way they want and then be able to hit a button to directly bake that geometry to a heightmap by rendering the current editor scene to a texture that is then saved as a game asset. The ortographic volume for this would be specified on the prefab that I'd create for the water simulation.
So, in short, my question is:
How can I trigger a render to texture of the current scene at editor time (and save this as an asset)? And, if possible, can I specify to render only objects with a given Tag (to avoid dynamic objects in the bake)?


texts:
Given three points,
(x1, y1, z1)
(x2, y2, z2)
(x3, y3, z3)

and given a point "A" at (x, y),
how would I find "A'", at (x, y, z)?


texts: Simple 2D games - what is faster to render - images or drawing?

texts:
I am developing simple 2D environment in Pygame (Python 3.6), however I think this question is general. The environment is moving (player is rendered on the same position and everything else is scrolling).

I have two ideas how to display the environment:

I can draw it with built-in functions - circles, rectangles, polygons (pretty much like simple HTML5 canvas).
I can load images (textures) and build the environment from them.

My questions:

What option is easier for CPU?
- Does it depend on resolutions of textures? Does it depend on how many elements I would draw instead of image?
Is there some general guideline what approach is better for what situation? Should I combine both approaches?

Should I care? The game will also contain a lot of other real-time computations - for example path-finding for various objects etc. So, should I even care about optimization of that simple 2D graphics?


texts: Why is my mouse disappearing at runtime?

texts: I'm using Unity 5.3.5f1 and every time I play my game in the editor, my mouse disappears. I really need to test some of my parameters in the inspector but I can't because the mouse is gone. How can I fix this, and if possible, make it permanent?


texts: Level and Player objects - which should contain which?

texts:
I've been working on a several simple games, and I've always come to a decision point where I have to choose whether to have the Level object as an attribute of the Player class or the Player as an attribute of the Level class.

I can see arguments for both:

The Level should contain the player because it also contains every other entity. In fact it just makes sense this way: "John is in the room." It makes it a bit more difficult to move the player to a new level, however, because then each level has to pass its player object to an upcoming level.

On the other hand, it makes programming sense to me to leave the player as the top-level object that is persistent between levels, and the environment changes because the player decides to change his level and location. It becomes very easy to change levels, because all I have to do is replace the level variable on the player.

What's the most common practice here? Or better yet, is there a "right" way to architecture this relationship?


texts:
First, I would like to say that I have no experience with this and am still getting my head around OOP, so if something is really obvious, just point it out :)

I am designing a game and I am not sure of the best OOP design patten to use or if I am going on the right track. I have entities, but I don't know the best way of storing them. I am going to put them in a vector based on what I have seen on GDSE, but am not sure where to put that in my games code. I thought of putting them in a singleton manager class, but have read up on singletons and don't think that it would be wise to use them.

Or could I store entities in a world object? Like here ?

Is a singleton entity manager class fine in this case, or can you point me in the right direction for a different way of managing them.

EDIT: Oops.Even though I did multiple searches only now have I seen this (http://tinyurl.com/kv963nu) Although this seems to tell me to use global variables or singletons..


texts: How can I avoid type checking in the physics side of collision handling?

texts:
I have a class responsible for handling the physics side of collisions. When the collision detector spots a collision, it notifies both entities in the collision to take care of gameplay. It also notifies the PhysicsGenerator to take car of the physics of the collision.

I don't know if it's possible to avoid type checking in the handleCollision() method of PhysicsGenerator. What I wanted to do is apply a force on both entities in the collision to push them backwards. But I can only do this if they are MovingEntities. What if one of them is a StaticEntity? In this case it should be treated differently. I don't know how I can do that without using instanceof quite a lot.

How is this usually handled?


texts: How to calculate the magnitude of the drag in Corona-sdk?

texts:
I'm making a game on Corona that launches a ball.

The force is based on the magnitude of the drag: the larger is the drag -> the higher is the force.

I'm having some trouble to do this, because I can't calculate the magnitude of the drag.

I tried a simple (finalX - initialX) but that's not a good idea.

local function onTouch(event)

    if "began" == event.phase then

    end
    if "ended" == event.phase then
        local finalX = event.x
        local finalY = event.y

        forceX = event.x - event.xStart
        forceY = event.y - event.yStart

        print(forceX, forceY)

    end
end

local function gameComponents()
    local crate = display.newImageRect( "images/sonic.png", 90, 90 )
    crate.x, crate.y = 60, 360
    crate.rotation = 0
    --physics.addBody( crate, "static", { friction=0.3} )

    Runtime:addEventListener( "touch", onTouch )
    return crate

end

local Game = {}
Game.new = gameComponents
return Game


texts: In Unity, how can I read the color from _LightColor0 in a shader?

texts:
I have a scene with a point light and alpha textured (RGBA) triangle strips. I want to apply the point light color with a shader.

Shader "Custom/Test02" {
    Properties {
        _MainTex("Texture (RGBA)", 2D) = "gray" {}
    }
    SubShader {
        Tags { "Queue"="Transparent" "RenderType"="Transparent"  }

        Blend SrcAlpha OneMinusSrcAlpha

        Pass {
            Tags { "LightMode" = "ForwardBase" }
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            uniform sampler2D   _MainTex;
            uniform float4      _LightColor0;

           struct vertexInput {
                float4 vertex   : POSITION;
                float4 texcoord : TEXCOORD0;
             };

            struct vertexOutput {
                float4 position : SV_POSITION;
                float4 color    : COLOR;
                float2 uv       : TEXCOORD0;
            };

            vertexOutput vert(vertexInput input) {
                vertexOutput result;

                result.position = mul(UNITY_MATRIX_MVP, input.vertex);
                result.uv       = input.texcoord;
                result.color    = float4(_LightColor0.rgb, 1.0f);
                // result.color    = float4(1.0, 1.0, 1.0, 1.0);
                return result;
            }

            float4 frag (vertexOutput input) : COLOR {
                float4 color = tex2D(_MainTex, input.uv);
                return color * input.color;
            }
            ENDCG
        }
    }
}

The color in _LightColor0 is always black. How do I get the proper point light color? If the color is set to float4(1.0, 1.0, 1.0, 1.0); everything appears but without color from the point lights.


texts: Move two different objects to two different destinations so they arrive at the same time without using lerp

texts:
I might be missing some simple thing but I'm not I am able to wrap my head around this. Normally, if I want to move two objects to different positions so they arrive at the same time I would use a lerp like so:

var speed = 2.0f;
var amount = Math.Min(1f, this.elapsedTime * speed);

var obj1NewPosition = Vector2.Lerp(this.obj1Start, this.obj1End, amount);
var obj2NewPosition = Vector2.Lerp(this.obj2Start, this.obj2End, amount);

this.obj1Position = obj1NewPosition;
this.obj2Position = obj2NewPosition;
this.elapsedTime += dt;

But I want to do this in a way where I only add to their positions:

var speed = 2.0f;

this.obj1Position += obj1Vector * speed * dt;
this.obj2Position += obj2Vector * speed * dt;

// obj1Vector is a normalized vector headed to obj1End
// obj2Vector is a normalized vector headed to obj2End

How do I make the second approach work such that each object will arrive at the destination I choose at the same time by only adding to their positions?

I don't have to consider acceleration or deceleration, simply: have two objects arrive at their respective destinations at the same time and then stop.


texts: How to Instantiate enemies (triangles) in the shape of an n sided polygon

texts:
I am trying to instantiate a cluster of triangles (enemies) in the shape of a polygon and am unsure how to angle them correctly to all be facing away from the center. Thanks to another question, I got the positions roughly right:

for (int i = 0; i < formation.Count; i++)
{
    Vector3 pos = new Vector3(Mathf.Sin((float)i / formation.Count * 2 * Mathf.PI), Mathf.Cos((float)i / formation.Count * 2 * Mathf.PI));
    GameObject tri = Instantiate(gameObj, pos, /*Quaternion.Euler(0, 0, z)*/, parent) as GameObject;
}

Now I just need to get the angles such that all triangles face away from the center.


texts: What are the advantages and limitations of using Qt for game development?

texts:
I know there is already a thread asking for example 3d games written using Qt. What I'd like to have a discussion about is whether or not Qt is a good framework for game development.

In my experience Qt is a joy to work with and thanks to QML and QML/3d it's looking like it could be a viable framework for game development. The thought of using signals and slots for gamedev is exciting.

I'd like to hear some opinions on Qt in general as a game development platform. What are it's limitations? What are it's advantages?

Edit: I found an official Qt game development forum.


texts:
This is my first time using interfaces so I imagine I'm doing something dumb.  I have an interface called ILoadable inside ILoadable.cs;

using UnityEngine;
using System.Collections;

public interface ILoadable {
    void AssetLoader();
}

I also have a couple scripts that implements the interface, here's the small one;

using UnityEngine;
using System.Collections;

public class InputRebinder : MonoBehaviour, ILoadable {

    string upKey;

    public void AssetLoader(){
        upKey = ",";
    }
}

Then I have a script that I want to call all the instances of AssetLoader throughout my game.

using UnityEngine;
using System.Collections;

public class InterfaceControl : MonoBehaviour {
    ILoadable loader;
    // Use this for initialization
    void Awake () {
        AssetInterface();
    }

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

    }
    void AssetInterface(){

        loader.AssetLoader();
    }
}

I want all my assets to load up when the game starts. Assets in this case being links to gameobjects, so I'm essentially running a bunch of gameobject.find~ and I want to be able to summon those at will. Instead of working as advertised I'm getting this error;

NullReferenceException: Object reference not set to an instance of an object
InterfaceControl.AssetInterface () (at Assets/Resources/Scripts/Interfaces/InterfaceControl.cs:18)
InterfaceControl.Awake () (at Assets/Resources/Scripts/Interfaces/InterfaceControl.cs:9)

Which I know means I need to have an instance of loader in my interfacecontrol script. I think I could probably put in

loader = new InputRebinder(); But I don't want to just call input rebinder I want to call any script that has the ILoadable interface.

'for reference, I was following the instructions on dotnetperls.com in the interfaces section.


texts: Development pace and Balancing RPG with multi-layer character building

texts:
a friend of mine and I have been working on an online RPG game where players get to build a character by allocating stats, selecting their abilities, and equipping gear before fighting each other in a sort of arena-style combat. There are currently four main stats that pertain to melee fighters with intentions of adding more stats for spell casters. We have decided the combat rules and decided what the ideal balancing should be between various possible builds at level one. After testing for a few weeks, we see results that significantly differ from our end goal.
As a junior agile developer working with a skilled, long time RPG player, our ideas on how to progress with the game differ slightly.
As stated, there are intentions to add multiple layers to this game.
With the characters being imbalanced at level one (balanced differently than anticipated), the question is:
would it be more efficient/effective in any way for us to move on from this (base stat aka layer one) balancing and instead balance our game when all of the layers are available, or to continue to tweak the balancing at layer one?
By this, I mean, at level one, a hunter may beat a warrior when the desired outcome is the other way around. However, once a knight is in a full suit of armor and equipped with more complex abilities, they would beat a hunter, this means at layer one, just counting the combat between opponents, using the same ability / no gear / same amount of stat points (allocated differently per build) a hunter beats a knight but after equipment and abilities are introduced the knight will beat the hunter which would be our desired outcome.
From an agile perspective, I understand the MVP concept of, try to get together an app quickly so it can start testing sooner. At the same time, it is essential to us that the game is fair (I understand this has to do with the rules) and that, at its core, it has a strong foundation. I am not scrum master and I'm not sure of - at what point do we move on if we aren't reaching our goal?
Neither of us are game designers so we would like to encourage responses from such viewers but all input is appreciated!


texts:
Does Google allow 3rd party payment solutions to be enabled in developers' apps (i.e., Paypal, carrier/SMS payment), especially in countries where Google Checkout isn't present? Or does this violate any policy of theirs?

Please reference the policy in your answer if you can, and thanks in advance to all who answer.


texts: Advanced Cellular Automata to generate caves

texts:
I am trying to make caves in Unity. To do this, I am trying to use cellular automata. I found the following (Rouge Basin Cellular Automata for Caves) that resembles what I am trying to accomplish.

However, the tutorial is not entirely what I want. I want something like what is produced by this website(Don Jon Caves) with the "cavernous" setting (see image below).

As you can see in the image, everything is connected. I have tried numerous methods and libraries, however nothing has worked.

I have been struggling with this issue for a while, and I would appreciate any guidance what so ever.

Thanks


texts: Replace glTranslatef and glRotatef with matrixes

texts:
I'm not an opengl expert, and, as a novice, I prefer to practice a little bit with the old opengl just to be sure to understand correctly the basic concept of computer graphics before deal with shaders and modern opengl (3.x). I don't want to start a flame with this so I'll go through my question. I just know that what I'm using is deprecated.

What I wanto to render is this:

and I'm drawing it using this piece of code:

// draw grid
drawGrid(10, 1);

// draw a teapot
glPushMatrix();
glTranslatef(modelPosition[0], modelPosition[1], modelPosition[2]);
glRotatef(modelAngle[0], 1, 0, 0);
glRotatef(modelAngle[1], 0, 1, 0);
glRotatef(modelAngle[2], 0, 0, 1);
drawAxis(4);
drawTeapot();
glPopMatrix();

Now, I'd like to replace the last glTranslatef and glRotatef with matrixes, and I'm doing in this way:

Matrix4 _matrixModel;
_matrixModel.identity();
_matrixModel.translate(modelPosition[0], modelPosition[1], modelPosition[2]);
_matrixModel.rotateX(modelAngle[0]);
_matrixModel.rotateY(modelAngle[1]);
_matrixModel.rotateZ(modelAngle[2]);

glLoadMatrixf(_matrixModel.getTranspose());

And I don't see anymore the teapot. So I thought that this _matrixModel is not complete because it is only the model matrix and I need a modelview so I have to multiply it with the projection matrix but.. this is what I get:

where am I wrong?


texts:
As far as I can tell, most games have some sort of "game state system" which switches between the different game states; these might be things like "Intro", "MainMenu", "CharacterSelect", "Loading", and "Game".

On the one hand, it totally makes sense to separate these into a state system. After all, they are disparate and would otherwise need to be in a large switch statement, which is obviously messy; and they certainly are well represented by a state system. But at the same time, I look at the "Game" state and wonder if there's something wrong about this state system approach. Because it's like the elephant in the room; it's HUGE and obvious but nobody questions the game state system approach.

It seems silly to me that "Game" is put on the same level as "Main Menu". Yet there isn't a way to break up the "Game" state.

Is a game state system the best way to go? Is there some different, better technique to managing, well, the "game state"? Is it okay to have an intro state which draws a movie and listens for enter, and then a loading state which loops on the resource manager, and then the game state which does practically everything? Doesn't this seem sort of unbalanced to you, too? Am I missing something?


texts: Why is my velocity increasing instead of decreasing?

texts:
I am learning to use point effectors in Unity!

Now I have a sprite that is being effected by this point effector and it all works fine alone. I have introduced the following code to give the player the ability to break free from the pull of the point effector as follows:

void FixedUpdate(){
    if (Input.GetKey (KeyCode.Space)) MoveOutwards();
}

void MoveOutwards() {
    Vector2 force = directionFromCentre () * 10f;
    rb2D.AddForce (force);
}

Vector2 directionFromCentre() {
    Vector2 dir = new Vector2 (transform.position.x,transform.position.y);
    dir /= dir.magnitude;
    return (dir);
}

To be noted the point effector is located at (0,0,0).
When my point effector is having a magnitude of -5f the player is able to move outwards. However when I put the magnitude of -20f he is not moving outwards, infact he is speeding up the motion towards the centre of the point effector!

I can't seem to understand why!? The players should actually slow down from moving towards the point effector.

Other details regarding the point effector:


texts: How to call StartCourotine in abstract class?

texts:
Bellow is my code. I have an abstract class and a inheriting class. This keeps giving me an NullReferenceException, on the StartCoroutine(WaitForTime) when Activate() is called on a InheritedClass instance. I can't figure it out.

public abstract class AbstractClass : MonoBehaviour
{
abstract protected string iD { get; }
abstract protected int CooldownSeconds { get;  }

protected bool IsInCooldown { get; set; }

public void Activate()
{
    if (!IsInCooldown)
    {
        TurnOn();
        StartCooldown();
    }
}

protected abstract void TurnOn();

public void StartCooldown()
{
    IsInCooldown = true;
    StartCoroutine("WaitForTime");
}

protected IEnumerator WaitForTime()
{

    yield return new WaitForSeconds(CooldownSeconds);
    IsInCooldown = false;
}

}

public class InheretingClass : AbstractClass
{
    protected override int CooldownSeconds { get => 30;}

protected override string collD => "Cool";

protected override void TurnOn()
{
    Debug.Log( iD + " Activated");
}
}


texts:
My ball is jumping on a 3d cylinder, and sometimes the ball gets stuck inside the cylinder. The ball has a rigid body and it's continuously dynamic. The circle also has a mesh collider.
Here is the code to make the ball jump:

void Update () {

    if(Mathf.Sign(rg.velocity.y)==-1){

        isforceApplied=true;
    }

}

void OnCollisionEnter(Collision collisionInfo)
{

    if(isforceApplied==true){

        isforceApplied=false;
        rg.AddForce(transform.up*forceAmount,ForceMode.Impulse);

    }

}


texts: Warcraft 3 Editor - Not triggering the Wait action?

texts:
Ok so this is mind boggling to me. Every time I've used something similiar before it works.  I added messages to be displayed before everything happened to see where it would, and it never got past the wait.

Events
     Unit - A unit Begins casting an ability
Conditions
     (Ability being cast) Equal to Berserking Power [E]
Actions
     Unit Group - Add(Triggering unit) to heroSpellUG[(Player number of (Owner of (Triggering unit)))]
     -Unit Group - Pick every unit in heroSpellUG[(Player number of (Owner of (Triggering unit)))]
           Unit - Add Berserking Power Damage to (Picked Unit)
           Unit - Set level of Berserking Power Damage for (Picked Unit) to (Level of Berserking Power [E] for (Picked Unit))
           Wait (5.00 + (Real((Level of Berserking Power [E] for (Picked Unit))))) game-time seconds
           Unit - Remove Berserking Power Damage from (Picked Unit)
           Unit Group - Remove (Picked Unit) from heroSpellUG[(Player number of (Owner of (Picked Unit)))]

So I guess my question is, why is the Wait not completing.  I had it display what the time to wait was and it said 6 seconds at level one. Any help would be appreciated.


texts: I want to model the earth 1:1 in unity, but I can only zoom to a certain value in the scne window of unity


texts:
This is not exactly game development, and I have also posted this in Arqade but it is development of a virtual playable version of a board game so maybe it loosely fits. Im hoping someone has an idea either way, or can point me to the right place to post this to get better results.

I am working to create a Tabletop Simulator mod for a newly Kickstarted game: Shiver Me Timbers.

https://www.kickstarter.com/projects/shivermetimbers/shiver-me-timbers-0/description

I have gotten all of the game pieces into the mod, all of the cards, tokens, tiles, I even made 3D models of the standees.

Where I am getting stuck is the pirate ship miniatures. These modular miniatures are what you use to move around the board. In the game one of the things you can do is upgrade your ship. When you upgrade the ship, or get damaged in some way, (IRL) you physically add or remove pieces from the mini (when you upgrade your hull you pull apart the front and back of the ship and add another hull section in between and put them back together, when you upgrade sails you add a different Mast to the ship, when upgrading cannons you push a new cannon into one of the holes in the side of the ship, when taking damage to any of these areas the opposite. You can see how this works in the different GIFs on the kickstarter page above). Each ship can have a maximum of up to 7 hulls, 7 sails, 7 cannons or any combination in between. Also each "hull" piece has a disk/wheel in it that determines what type of cargo you are carrying.

The problem I am running into is making the different components come together in a way that 1. stays together when moved, 2. is able to later be removed, and 3 allows for the disks to rotate/change as needed.

I originally thought about just using different states for each configuration of the mini but that would turn out to be 343 states for just the ship (not to mention the 4 positions each cargo disc can be in) and creating that many states for one mini would not only take an insane amount of time making the 3D models, but would be a HUGE number of assets for the game to load, and be extremely confusing when trying to find the correct state for the configuration you need.

I did decide (potentially incorrectly) to have set it up to use states for the 7 different hull configurations, and use the fixed joint tool to attach the cargo disks and that works, as long as you have each hull state set to be attached to the disk, or if you have each disk state (4 different states for the cargo types) set to attach to the base. But if I have both items having multiple states if I change the one that the Joint is going TO then it breaks and the disks fall out.

The other issue with the mini's is attaching Sail Masts and Cannons. If I bring in the basic ship base and attempt to add a piece to it (aka one of the masts) I can create a snap point that allows it to fit to the correct spot but it always immediately falls over and off of the ship.

I have thought about using the attach tool, but once you place the new part onto the base of the mini, by the time you can get to the attach tool and use it the new part has fallen off or fallen over. It cant just be pre-done (with a gizmo on a locked object or something) because the players have to be able to modify mid game.

I have enough ability with blender to work these models some (though still a bit of a beginner) and I have been trying to learn unity so that I can use the higher poly count ship models (the texturing was done with 3D geometry not a texture png) and set them up to be asset bundles. I have done a tiny bit of work with collider geometry in blender/unity. I also have a minor amount of programming ability and could muddle through learning LUA and doing some scripting to make it work if that is the solution.

Does anyone have any ideas how to make these "Modular" mini's a reality in the virtual space of TTS? Any Ideas are welcome. I Really want to figure this thing out. Thanks in advance.


texts:
Hi I started today to make an OpenGL program, I made the shader class, mesh class and texture class. When I tried to test it, it stopped working. After a little debug with Visual Studio(thanks Microsoft for this useful tool). It showed me that my problem is:

glGenVertexArrays(1, &m_vao);

I use glew. I searched on internet, and I found that glewExperimental needs to be GL_TRUE, so I init it like this:

glewExperimental = GL_TRUE;
GLenum error = glewInit();
if (error != GLEW_OK)
    std::cerr << "Glew: " << glewGetErrorString(error);

nothing changed.

Error given by Visual Studio:

Exception thrown at 0x00000000 in DirtyCraft.exe: 0xC0000005: Access violation executing location 0x00000000. occurred

I do use Glew 2.0.0, 32-bits, SDL2.

If you need any additional information, feel free to request them.


texts: How can I find a good fixed ratio between buying and selling prices for the player in an in-game market?

texts:
I'm developing a single player game containing gathering and crafting where I'm still struggling to find base values for the prices of gathered resources and crafted items. (But this is part of Constructing a game stock market)
Since it's a single player game and just one in-game market that offers items, I do not want to use dynamic pricing, I'm looking for a reasonable ratio between the buying and selling price. I was not able to find any hints on how to determine a good starting point.
Is for example 2:1 a reasonable ratio between the buying and the selling price for the player?
Things to consider:

Of course the buying price has to be higher than the selling price or otherwise players could just make fortune by buying and selling the same item.
Only some randomly chosen items will be available to buy in a certain time period and rarer items will be seen less often in the shop to buy.
The offer should be reasonable enough to tempt the player to buy the item instead of farming the ingredients and craft the item for themselves.

Updated the question to fit the constraints.


texts:
I'm using unity2D and C#, and I have a code for touch screen:

if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Began)
        {
            startTime = Time.time;
            startPos = touch.position;

        }
        else if (touch.phase == TouchPhase.Ended)
        {
            endTime = Time.time;
            endPos = touch.position;
            swipeDist = (endPos - startPos).magnitude;
            swipeTime = endTime - startTime;

            if (swipeTime < maxTime && swipeDist > minSwipeDist)
            {
                swipe();
            }

And this code for swipe:

void swipe()
{
     Vector2 distance = endPos - startPos;
    if (Mathf.Abs(distance.x) > Mathf.Abs(distance.y))
    {
           if (distance.x > 0)
        {
            Debug.Log("Right swipe");
        }
        if (distance.x < 0)
        {
            Debug.Log("Left swipe");
        }
    }
    if (Mathf.Abs(distance.x) < Mathf.Abs(distance.y))
    {
        if (distance.y > 0)
        {
            Debug.Log("Up swipe");
        }
        if (distance.y < 0)
        {
            Debug.Log("Down swipe");
        }
    }
}

}

How can I add to this code hold function, for for example move object at the screen?


texts: Crate destroy when in trigger and button E pressed

texts:
There are no errors in the console but I feel like im doing something wrong. The crate is not destroying when I click E.
public class CrateDestroy : MonoBehaviour
{
    public GameObject crate;

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                Destroy(crate);
            }
        }
    }
}


texts: Unity 2d square position not lining up with its size

texts:
I want to have one square that rests at the Unity 2d coordinates (5,5). Using transform.localScale I make the square be 3 units by 3 units large. So I thought that if I made another square that is the exact same except it is at the coordinate (8,5), the second square would be directly to the right of the first one, touching it. But instead, the square spawns a bit more to the right than it should, implying that the size x,y units are smaller than the position x,y units. Any way I can solve this problem, and have both touching? Thank you.

Code for placing the squares (tileHeight = 3 and tileWidth = 3):

GrassTile.transform.localScale = new Vector3(tileWidth, tileHeight, 0f);
Instantiate (GrassTile, new Vector3 (0f, 15f, 0f), Quaternion.identity);
Instantiate (GrassTile, new Vector3 (3f, 15f, 0f), Quaternion.identity);

Screenshot of what it looks like, as well as what the prefab looks like:

Screen shot of the grassTile stats:


texts: How to handle mesh update in its vertex buffer

texts:
suppose i have a mesh, it can undergo any kind of changes - bend, stretch, even been torn. How should i update vertex buffer in DirectX for this mesh. For now i recreate it every time, and i don't see any chances for another approach because i don't know what part of vertices array can change between steps.

Is there any known approaches for this problem?


texts: I'm trying to populate a Array of Static Meshes from the On Begin Play event with all the static meshes that are children of the primary object but can't seem to access them as static meshes, any suggestions?


texts: Design leaderboard ratings for quiz games

texts:
Back in March 2011 i started the following post: How to design a leaderboard?

Now my quiz game have been out for approximately a year and sold pretty decently. I am working on to update the game design and is again looking into the leaderboard design to make it better as i am not happy with it.

Currently i rate players on number of correct answers, which is not good as it does not consider things like number of games, difficulty levels etc. I also have "extended" stats behind the UITableView (Leaderboard).

A player can play based on three levels of difficulty: hard, medium or easy
Difficulty levels can be mixed between players in a game
Each game can be one to six players, so there can be single games or duels
Between 2 and 30 questions per game

As i am considering integrating Game Center Leaderboard i need to design a better rating system so i would like to ask for some ideas how to do the rating based on the above.

I am thinking about how much a point would be worth and what it includes.


texts: Transactions on lists of coins of different values

texts:
For learning purposes, I am developing the first steps of an idle game with exponentially higher income numbers. Usual int, long, etc. can't store big enough numbers for that.
I looked through many threads which I found on google and using a list (or an array) which is separated in e.g. bronze coins, silver coins, gold coins, etc. seems to be the cleanest version.
In my first approaches I created this list:
namespace Coins
{
    public class script_coinHandler : MonoBehaviour
    {
        public List<Coin> coinList = new List<Coin>() // list based on the "Coin" class
        {
            new Coin() { Name = "bronze"},
            new Coin() { Name = "silver"},
            new Coin() { Name = "gold"},
            new Coin() { Name = "diamond"},
        };
    }

    public class Coin
    {
        public string Name { get; set; }
        public int Amount { get; set; }
        public int Multiplier { get; set; }
    }

}

I want each coin type to go up to 999999. This means 1 silver = 1000000 bronze, 1 gold = 1000000 silver.
I can't get my head around a way to do maths with this list.
Example:
Player has 3000 GOLD, 320000 SILVER, 524321 BRONZE
Player wants to buy something for 20 GOLD, 120000 SILVER, 300000 BRONZE
Just subtracting 20 from GOLD, 120000 from SILVER, and 300000 from BRONZE won't always work. For example when a Player has no BRONZE but some SILVER - you can't subtract 300000 BRONZE without converting SILVER to BRONZE first.
Q: What would be an efficient function to subtract the price from the total amount? What about multiplying and dividing?
Accuracy is not important. When spending a few GOLD, nobody will care about 10000 BRONZE.


texts: Unity3d - deploy game to android device off site

texts: I am using Unity3d to develop my game and my friend with android device wanted to test it. I am natively IOS developer and have no knowledge of deploying Android platform. What do I need other than Unity3d? The scenario here is that I have to send to my friend who is not developer to install and test on his device via internet. We used to have TestFlight App but that is history now.


texts:
The flow I see people discussing using is the following

In your build asset bundles step, grab the hash of each bundle
Store that on your server somewhere
Fetch those hashes at runtime
Use the Caching.IsVersionCached with that hash to detect if you already have a bundle
If not download the bundle and cache it
success

If this is how you are supposed to do it, why does the main mainfest(example Android.manifest) which can be loaded into a class AssetBundleManifest, have a function to get the hashes for you: unity doc
I was able to just use that technique up until now, but I have hit a problem where it failed to detect a hash change properly and that function is not giving me back the same hash that I see in one of my other bundles .manifest file
Hashes:
AssetFileHash:
serializedVersion: 2
Hash: a44a4d42247721b8bd6f32531f73f9e3
TypeTreeHash:
serializedVersion: 2
Hash: ea5a42e0fd8ea905efa7aa926a3b8944
I am under the impression that the first value above is what would should match what you had stored on your server.


texts:
I want to render my scenes as equirectangular panorama frames.

I can get the angular fisheye which is what I actually need by applying the rendered frame as a texture to a correctly UV mapped circle.

But how can the scene be rendered as equirectangular panorama?

I'm using a 3d engine which uses OpenGL and GLSL.


texts: Creating a Custom Map Editor using XNA and Windows Forms

texts:
I'm looking to create my own level editor for a game I'm making, and I came across the following post:

Tutorial or Example of creating custom sprite tool/map editor for XNA?

In the example posted by Blau, I am unsure what needs to be replaced in this line, and with what:

XnaControlGame.CreateAndShow<MainDialog, VoxelEditorGame>( );

If anyone could help at all, that would be great!


texts: Unity Animator animations fail to play only when triggered by user input

texts:
I have a unity animator setup like so. When the game runs, I can trigger each state in the state machine with user input. I can use HasExitTime flag to trigger the animation, and it will play through and loop infinitely as expected.
However, when I try to use the GearChange trigger, the state machine progress bar plays, the correct box is triggered, but the animation itself doesn't play! I'm at a total loss as to what the problem is here, as everything else is exactly the same, minus the user input.
The console isn't showing any errors, the animation simply doesn't respond to the state machine. What am I missing here?
Unity version 2020.1.0f1
So I deleted the animator, and setup everything again the exact same way. Now the animation won't play, period. The state machine progress bars are still triggered as expected, but the animation won't play.
In the transition preview, the animation won't play there either.


texts: Is it safe to use Sleep() in game loop (on Windows)?

texts: Is it safe to use Sleep() function on Windows in game loop (C++)? I want to have fixed frame rate.


texts: How to draw 2D images using OpenGL, in SDL?

texts:
After everything, I managed to find a simple piece of code that shows how to draw a 2D image with openGL:

    #include "SDL/SDL.h"
    #include "SDL/SDL_opengl.h"
    #include "SDL/SDL_image.h"

    const int SCREEN_WIDTH = 640;
    const int SCREEN_HEIGHT = 480;
    const int SCREEN_BPP = 32;

    int tex;

    int loadTexture(char* fileName){
        SDL_Surface *image=IMG_Load(fileName);
        SDL_DisplayFormatAlpha(image);
        GLuint object;
        glGenTextures(1,&object);
        glBindTexture(GL_TEXTURE_2D,object);
        glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
        glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,image->w,image ->h,0,GL_RGBA,GL_UNSIGNED_BYTE,image->pixels);
        SDL_FreeSurface(image);
        return object;
    }
    void init(){
        glClearColor(0.0,0.0,0.0,0.0);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0,800,600,1.0,-1.0,1.0);
        glEnable(GL_BLEND);
        glEnable(GL_TEXTURE_2D);
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
        tex = loadTexture("hi.png");
    }
    void draw(){
        glClear(GL_COLOR_BUFFER_BIT);
        glBindTexture(GL_TEXTURE_2D,tex);
        glBegin(GL_QUADS);
            glTexCoord2f(0,0);
            glVertex2f(0,0);
            glTexCoord2f(1,0);
            glVertex2f(500,0);
            glTexCoord2f(1,1);
            glVertex2f(500,500);
            glTexCoord2f(0,1);
            glVertex2f(0,500);
        glEnd();
        glFlush();
    }
    int main(int argc,char** argv){
        SDL_Init(SDL_INIT_EVERYTHING);
        SDL_Surface* screen=SDL_SetVideoMode(800,600,32,SDL_SWSURFACE|SDL_OPENGL);
        bool running=true;
        Uint32 start;
        SDL_Event event;
        init();
        while(running){
            start=SDL_GetTicks();
            draw();
            while(SDL_PollEvent(&event)){
                switch(event.type){
                    case SDL_QUIT:
                        running=false;
                        break;
                }
            }
            SDL_GL_SwapBuffers();
            if(1000/60>(SDL_GetTicks()-start))
                SDL_Delay(1000/60-(SDL_GetTicks()-start));
        }
        SDL_Quit();
        return 0;
    }

I'm inexperienced in 2D, and about a week ago started messing with SDL. Built some simple structures to have images, which would be on layers, so I could have my own drawing order, so sprites would be drawn after background, etc, and then did a little "sprite engine".
I got a Megaman sprite walking left and right just like I wanted it, above a simple 900x900ish background image.

Thing is, CPU almost reached 20% on my i5... so I thought of using the graphic card to do the drawing! Delved abit into OpenGL and today, finally managed to get gl3w working!

So now I'm looking for a simple way to display my sprites/images, on the window, through use of OpenGL. I've tried all sorts of code I ran across, but I can't get anything displaying, despite that I've done error checks basically everywhere, and everything seems to check out to be right!

TL:DR; I was looking for some simple working code, using SDL, on how to draw 2D images (which, if it doesn't work, for sure I've got something wrong).

Thanks!


texts: Pass parameters from html page to start() function in unity3D webplayer application

texts: I want to pass a parameter from web browser to Unity3D web player as soon as it is loaded. I know that, as soon as the web-player is loaded, the start() function is execute inside web-player. So I want to pass parameter from  web browser to this start() function.


texts:
I am using pygame on a mac, and when the app runs, it draws a frame of the screen fine, and then crashes with the following error:

Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree),
function NSViewSetCurrentlyBuildingLayerTreeForDisplay,
file /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1561.10.101/AppKit.subproj/NSView.m,
line 14480.

Everything was working fine, but I did switch to multi-threading, and I think this might be related.  Has anyone a clue as to what might be going wrong?

I call:

pygame.init()
pygame_size = 1280, 960  # image dimensions
pygame_screen = pygame.display.set_mode(pygame_size)

in the main thread, and then I have many pygame draw calls.


texts:
I am trying to both A.) Pinch zoom my game scene and B.) Move (scroll) my game scene but I have not found many examples. I learn more by examples than by reading API documentation (although I am willing to resort to that if there is no other way) and the lack of examples has put a damper on my game.

How do I do these things?

A little background:

I am developing a RPG for Android and one of the features in my game is the ability to purchase a game map for money that let's users see the location of enemies in the level and all of the obstacles. Since most Android devices are quite small 3.5" to 5" I thought it would be a good idea to let the user zoom into the map and then scroll around. I have omitted most of my game code.

Relevant code

I have

 //Irrelevant code omitted for clarity and in accordance with the help center
    public class MyGdxGame implements ApplicationListener
    {
Texture mapTexture;
SpriteBatch batch;

@Override
public void create(){
    mapTexture = new Texture(Gdx.files.internal("map.png"));
    batch = new SpriteBatch();
}

@Override
public void render(){
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.glClear(GL20_GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(0 , 0, Gdx.graphics.getWidth, Gdx.graphics.getHeight());
    batch.end();
}

@Override
public void dispose(){
}

//I want to zoom in to the map here
@Override
public void resize(int width, int height){
}

@Override
public void pause(){
}

@Override
public void resume(){
    }
}


texts: Unity Android build fails, error : Could not find com.android.tools.build:gradle:x.x.x

texts:
Can't build for Android, error log:

CommandInvokationFailure: Gradle build failed,

And this is in it's description:

Could not find com.android.tools.build:gradle:3.2.0.


texts: Counting no.of bodies present in certain area in box2d?

texts: I am stuck on it:how can i count or find the no.of bodies present in any area in as3?would be thankful if any guys help me out.....


texts: Deriving from base class but not calling base method

texts: I am very new to C#, XNA, and OOP. This is my question: I have an abstract class called Sprite. Sprite handles position and drawing from the sprite sheets, from its update and draw methods, for my other automated and user controlled classes. I have another class that I need to create that also uses a sprite sheet but not in the same way. The sprite sheet in this case shows the texture in 5 states, from whole to destroyed, and I am going to write the update method for it so that when a missile collides with the texture, then and only then does the next frame of the sprite sheet get drawn. Is there a way that I can have this class, called bunker, be a child of the sprite class but never call the update method from the parent? Or should I just make it a seperate class altogether? Thank you for bearing with my noobish question.


texts:
I've read some material about deferred rendering, and I think I get the gist of it. But what I don't understand is how it accomplishes shadows. The G-buffer, as far as I'm aware, does not involve creating a shadowmap for each light, so I'm confused as to how the lighting pass is aware of whether or not each pixel is occluded. After all, a given pixel which is visible from the camera's perspective may not actually be visible from the perspective of any given light- and that occluding geometry may not be visible from the camera's perspective and therefore have nothing written about it into the G-buffer.

If you start rendering shadowmaps, then it seems pretty much the same as forward rendering- you render all the geometry in the scene for every light to render the shadowmaps.

So how does deferred rendering accomplish shadows equivalent to forward rendering?