texts: Create a new Surface type with SDL_Texture

texts:
So I started using Awesomium, and I'm experiencing some difficulties.

I want to create a new type of Awesomium::Surface and implement it in my custom Awesomium::SurfaceFactory to render Awesomium::WebView->surface as SDL_Texture.

I'm currently stuck at the Paint function which is supposed to update some pixels, so I have this (in the project it's separated in header and definitions):

class AwsSurface {

    public:
    AwsSurface(int w, int h) : public Awesomium::Surface {
        // _renderer is my global renderer, on Awesomium DOCs it says that pixels are
        // "in 32-bit BGRA format" so I guess the format is right...
        texture = SDL_CreateTexture(
            _renderer,
            SDL_PIXELFORMAT_BGRA8888,
            SDL_TEXTUREACCESS_STREAMING,
            w,
            h
        );
        dst_rect = {0, 0, w, h};
    }

    void Paint(unsigned char* src_buffer,
             int src_row_span,
             const Awesomium::Rect &src_rect,
             const Awesomium::Rect &dest_rect) {
    }

    protected:
    SDL_Texture* texture;
    SDL_Rect dst_rect;
};

I'm not sure if I get it right, but fromwhat the DOCs say if I'm given a src_rect={2, 1, 2, 3} and src_row_span=20 I am in this situation, right?

Now, I understood how the buffer works (more or less), but I don't know how to copy the pixels from it onto my texture (in the given position).

Edit: I came up with this paint function:

void AwsSurface::Paint(unsigned char* src_buffer,
                       int src_row_span,
                       const aws::Rect &src_rect,
                       const aws::Rect &dest_rect) {
    Uint32* src_buffer_i = (Uint32*)src_buffer;
    src_row_span /= 4;
    int dest_row_span;
    Uint32* dest_buffer;
    SDL_Rect r = AwsRectToSDL(dest_rect); // Custom function to convert the rect
    SDL_LockTexture(
        texture,
        &r,
        (void**)&dest_buffer,
        &dest_row_span
    );
    dest_row_span /= 4;
    for (int x = 0; x < src_rect.width; x++) {
        for (int y = 0; y < src_rect.height; y++) {
            Uint32* s = src_buffer_i + (src_rect.y + y) * src_row_span + src_rect.x + x;
            Uint32* d = dest_buffer + (dest_rect.y + y) * dest_row_span + dest_rect.x + x;
            *d = *s; // Here happens the exception
        }
    }
    SDL_UnlockTexture(texture);
}

But I get an "access violation on writing" exception on the line above, this happens after some successful executions (usually 6/7) and every time on the same rectangle {0, 0, 466, 26}.


texts: How can I make caves with Unity's terrain creator?

texts:
With Unity's terrain creator, I can't simply make a "hole" on the mesh.

I don't know how I would make cave-like structures other than using "rock" meshes for the roof (wich will indeed look weird) or using portals (wich I always have problems with -- the teleportation isn't thruly smooth and there's always a small "jump". You know, not like a fluid thing.

How can I make caves in terrain with Unity?


texts: Android: How to create fluent animations by using bitmaps and ObjectAnimator?

texts:
I want a resized bitmap item to move over the screen into a house. This basically works, but the movement is not fluent and is stuttering. Since I always have to draw both the resized background and the house due to some alphas (both are exactly as big as the screen), the animation runs very slow, because invalidate() is no fast enough. At every bitmap move, invalidate() is being executed.

This is a very simplified example of my view to show what I'm doing.

public class GameView extends View implements ValueAnimator.AnimatorUpdateListener
{
    //more code

    @Override
    protected void onDraw(Canvas canvas)
    {
        canvas.drawBitmap(ResizedBitmapMapping.getBackground(), 0f, 0f, null);
        canvas.drawBitmap(item.getBitmap(), item.getXY().getX(), item.getXY().getY(), null);
        canvas.drawBitmap(ResizedBitmapMapping.getHouse(), 0f, 0f, null);
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation)
    {
        invalidate();
    }

    public void setActive()
    {
        item = new Item(ResizedBitmapMapping.getItem());
        XYHolder startXY = new XYHolder(0f, height);
        XYHolder endXY = new XYHolder(width * 2 / 3, height / 4);

        animator = ObjectAnimator.ofObject(car, "xY", new XYEvaluator(), startXY, endXY);
        animator.setDuration(2000);
        animator.addUpdateListener(this);
        animator.setRepeatCount(ObjectAnimator.INFINITE);
        animator.start();
    }

    //more code

}

My questions:
Is the concept of drawing basically wrong? If yes, how does an efficient drawing concept look like?
If the concept is right, is it just a case of optimizing like drawing just "rects" instead of the whole background and house or something?


texts:
I am writing game in XNA 4 and this version have two profiles hi-def and reach. My problem is that I need to have my game code for each of these profiles and is very uncomfortable to have two projects and do all changes in both of them. My idea was to use preprocessor directive (i am not sure about name of this, http://msdn.microsoft.com/en-us/library/ed8yd1ha%28v=vs.71%29.aspx) and use IF statement at places with problems with profile. There is only problem that program needs to be compiled two times (for each profile) and manually changed directive and project settings to another profile.
And my questions are: Is that good way? Is there better and cleaner way how to do this?


texts: Workflow to have character look like : Tokyo ghoul:re [Call to exist]

texts:
I am looking into a lot of different software and now that I got my head around most of them, I was asking mysel if someone knew what has been used to create the characters in the game I mentionned.

Not specifically software if there is no information about it, but at least as it been modeld/sculpted, etc.

Thanks


texts: Most efficient way to get the world position of the 8 vertexes of a Box Collider (C#)

texts:
What I am looking for is the most efficient way to get the world position of the 8 vertexes of the Box Collider of a freely rotated Gameobject. I cannot use collider.bounds since object is rotated, not axis-aligned.

As for the framework I am working within, it's Unity 5 with C#.

Would you know how could I achieve that? Thanks in advance.


texts: Simple 2D vehicle physics - maintaining vehicle length

texts:
I'm learning OpenGL and trying to make a simple simulation, which involves vehicles (drawn just as a rectangles) moving along predefined path.
I've already read a few tutorials about designing a simple 2d car physics and tried to code something from a scratch.

Basically, I want to use a simplification so called a bicycle model - we assume that the car has just two wheels - one at the front in the middle to steer, and one at the back in the middle that cannot steer.

Moreover, the 'front wheel' is also a vehicle's current position. (possition is at front, not in the middle as usual).

It looks like this:

mainAxis[0] is the front wheel, mainAxis[1] is the back wheel

In most cases like described here or here, wheel movement is based on steer angle, which is fine when dealing with vehicle controlled by user input, but in my case I think I already have the direction of current front wheel movement - next node on the path.

This is how my movement function looks like for now: (I rewrote it in pseudo-code to simplify)

I know it does not involve factors like steering forces, friction or speed reduction before turning. I'd like to make vehicle position to update properly first.

// _deltaTime - time between frames
// velocity - vehicle speed (scalar value)

void updatePosition(double _deltaTime)
{
    //Front wheel is moving in direction of current target, while back wheel is moving along the 'previous' vehicle direction

    Vector2 oldPosition = currentPosition;

    Vector2 newPosition = currentPosition + normalize(currentTarget - currentPosition) * velocity * _deltaTime);

    currentPosition = newPosition;
    mainAxis[0] = currentPosition;

    mainAxis[1] += normalize(oldPosition - mainAxis[1]) * _deltaTime * velocity;

}

The vehicle turns fine, front wheel position is correct, however it doesn't maintain the baseline (vehicle length), that is, the distance between the front and rear wheel.

Turning looks more less like this:

(red rectangle is a vehicle, with mainAxis marked as black line and current velocity to target as white line)

I struggle to find a correct way to calculate wheels movement in a realistic way, i.e with preserving the car length (which is predefined).

Perhaps I should calculate back wheel movement reduction or move front wheel further...

Thank you in advance for any assistance


texts: Copyrights and Usage of 3rd Party Intellectual Property

texts:
I develop a game for a mobile platform. I would like to implement a movie figure/creature/character/vehicle into the game.

I wish to ask about Copyrights:

Is it acceptable, if I implement famous movie-like creatures (ex: Alien, Predator, Star Ship vehicle) into my game? Occasionally, I see games based on movies: "Star Trek, Star Wars, James Bond, etc..". If I wish to create a game based on successful movie, do I have to obtain approval?

What about songs? If I legaly purchase a CD in the store, can I use the song into my game?

Are there any conditions, under which I can use movie-like characters in my game? For example, if the game is going to be shareware/freeware, if the reneues does not exceed certain amount, or if some percentage of the original character look is modified?


texts: Dynamic libraries are not allowed on iOS but what about this?

texts:
I'm currently using LuaJIT and its FFI interface to call C functions from LUA scripts. What FFI does is to look at dynamic libraries' exported symbols and let the developer use it directly form LUA. Kind of like Python ctypes.

Obviously using dynamic libraries is not permitted in iOS for security reasons. So in order to come up with a solution I found the following snippet.

/*
(c) 2012 +++ Filip Stoklas, aka FipS, http://www.4FipS.com +++
THIS CODE IS FREE - LICENSED UNDER THE MIT LICENSE
ARTICLE URL: http://forums.4fips.com/viewtopic.php?f=3&t=589
*/

extern "C" {

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

} // extern "C"

#include <cassert>

// Please note that despite the fact that we build this code as a regular
// executable (exe), we still use __declspec(dllexport) to export
// symbols. Without doing that FFI wouldn't be able to locate them!

extern "C" __declspec(dllexport) void __cdecl hello_from_lua(const char *msg)
{
    printf("A message from LUA: %s\n", msg);
}

const char *lua_code =
"local ffi = require('ffi')                   \n"
"ffi.cdef[[                                   \n"
"const char * hello_from_lua(const char *);   \n" // matches the C prototype
"]]                                           \n"
"ffi.C.hello_from_lua('Hello from LUA!')      \n" // do actual C call
;

int main()
{
    lua_State *lua = luaL_newstate();
    assert(lua);
    luaL_openlibs(lua);

    const int status = luaL_dostring(lua, lua_code);
    if(status)
        printf("Couldn't execute LUA code: %s\n", lua_tostring(lua, -1));

    lua_close(lua);
    return 0;
}

// output:
// A message from LUA: Hello from LUA!

Basically, instead of using a dynamic library, the symbols are exported directly inside the executable file.

The question is: is this permitted by Apple?

Thanks.


texts: Creating a retro-style palette swapping effect in OpenGL

texts:
I'm working on a Megaman-like game where I need to change the color of certain pixels at runtime. For reference: in Megaman when you change your selected weapon then main character's palette changes to reflect the selected weapon. Not all of the sprite's colors change, only certain ones do.

This kind of effect was common and quite easy to do on the NES since the programmer had access to the palette and the logical mapping between pixels and palette indices. On modern hardware, though, this is a bit more challenging because the concept of palettes is not the same.

All of my textures are 32-bit and do not use palettes.

There are two ways I know of to achieve the effect I want, but I'm curious if there are better ways to achieve this effect easily. The two options I know of are:

Use a shader and write some GLSL to perform the "palette swapping" behavior.
If shaders are not available (say, because the graphics card doesn't support them) then it is possible to clone the "original" textures and generate different versions with the color changes pre-applied.

Ideally I would like to use a shader since it seems straightforward and requires little additional work opposed to the duplicated-texture method. I worry that duplicating textures just to change a color in them is wasting VRAM -- should I not worry about that?

Edit: I ended up using the accepted answer's technique and here is my shader for reference.

uniform sampler2D texture;
uniform sampler2D colorTable;
uniform float paletteIndex;

void main()
{
        vec2 pos = gl_TexCoord[0].xy;
        vec4 color = texture2D(texture, pos);
        vec2 index = vec2(color.r + paletteIndex, 0);
        vec4 indexedColor = texture2D(colorTable, index);
        gl_FragColor = indexedColor;
}

Both textures are 32-bit, one texture is used as lookup table containing several palettes which are all the same size (in my case 6 colors). I use the source pixel's red channel as an index to the color table. This worked like a charm for achieving Megaman-like palette swapping!


texts: OpenGL Textures: Texture contains color lines when object is further away that some distance

texts:
I tried searching on the web but couldn't find a reason for this. When I render an object close to the camera, the object and texture renders fine. But further away from a fixed distance, it starts showing weird color lines on the texture.

Close to the camera, no lines:

Further away, color lines appear on texture:

My shaders are pretty simple.

#version 330 core

layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 tex;

uniform mat4 projMatrix;
uniform mat4 viewMatrix;

out vec2 uvCoord;

void main()
{
    gl_Position = projMatrix * viewMatrix * vec4(pos.xyz, 1.0f);
    uvCoord = tex;
}

#version 330 core

out vec4 FragColor;

uniform sampler2D texture1;

in vec2 uvCoord;

void main()
{
    FragColor = texture(texture1, uvCoord);
}

My texture parameters are:

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

Any help would be appreciated!

Edit: I have generated mipmaps using glGenerateMipmap(GL_TEXTURE_2D)


texts: How do I extend Irrlichts scene manager?

texts:
If I want to extend the scene manager, and add a function; do I extend my class from CSceneManager or ISceneManager?

I'm trying this in MySceneManager.h:

#include <CSceneManager.h>

class RTSSceneManager : public CSceneManager
{
    virtual ICameraSceneNode* addCameraSceneNodeRTS(ISceneNode* parent = 0,
            const core::vector3df& position = core::vector3df(0,0,0),
            const core::vector3df& lookat = core::vector3df(0,0,100),
            s32 id=-1, bool makeActive=true) = 0;
};

But it's giving me this error:

fatal error C1083: Cannot open include file: 'CSceneManager.h': No such file or directory

It works if I use ISceneManager instead of CSceneManager, but then won't I have to re implement CSceneManager over again?


texts: Non-GPU Noise for 2D side-view terrain generation?

texts:
I really couldn't find a correct answer while scowering all the forums for Noise Generation.

My goal is simple, I really want to have two distinct layers for my terrain, a white layer representing air, and a black layer representing earth. An algorithm will pick up from there.

Most noise I found generated "Cloudy" textures, where I am looking for something along the lines of:

So far I have worked with Perlin Noise but adjusting my values yields no useful results.

Does anyone have any ideas?


texts: How to "reload" a TTF Text during runtime?

texts:
As the title says I would like to know how to reload a TTF_SDL Text during runtime in C++.

What I want to do is to update all the values of the text each frame so I can, to example change the font size and it will instantly change it in-game as well without needing to restart the entire game.

How would I do this?

Note : I'm using textures to render the text, using the SDL_CreateTextureFromSurface() function.

This is the way I'm currently trying to update the TTF Text :

void Text::Update(SDL_Renderer* renderer)
{
    SDL_FreeSurface(m_surface);
    SDL_DestroyTexture(m_texture);

    m_surface = new SDL_Surface();

    m_surface = TTF_RenderText_Solid(m_font, m_text.c_str(), m_color_fg);
    m_texture = SDL_CreateTextureFromSurface(renderer, m_surface);
}

And in the header file the two variables look like this :

SDL_Surface* m_surface = nullptr;
SDL_Texture* m_texture = nullptr;

And I currently get an error at SDL_FreeSurface(m_surface); which looks like this :

  Thread 1: EXC_BAD_ACCESS (code=EXC_l386_GPFLT)

However, the code can also be 1 with a address that seem to change every time I run my application

However I sometimes get another error on this line :

m_surface = TTF_RenderText_Solid(m_font, m_text.c_str(), m_color_fg);

Instead, which has the following error code :

  Thread 1: EXC_BAD_ACCESS (code=1, adress=0x11)

But the address on the error codes are not the same every time I run it.

(On both lines of code)

 **Full sprite class code :**

Sprite.hpp :

//
//  Text.hpp
//  SDL_Project
//
//  Created by Someone... on 2016-03-18.
//  Copyright © 2016 Someone... All rights reserved.
//

#ifndef Text_hpp
#define Text_hpp

#include <stdio.h>
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2_ttf/SDL_ttf.h>

class Text {

public:

    Text(std::string __m_text, int x, int y, SDL_Renderer* renderer);
    void Render(SDL_Renderer* renderer);
    void Update(SDL_Renderer* renderer);

    void SetText(std::string text, SDL_Renderer* renderer);

    void Destroy();

private:

    SDL_Rect* m_rect = nullptr;
    SDL_Surface* m_surface = nullptr;
    SDL_Texture* m_texture = nullptr;
    SDL_Color m_color_fg;
    TTF_Font* m_font;

    std::string m_text;

};

#endif /* Text_hpp */

Sprite.cpp :

//
//  Text.cpp
//  SDL_Project
//
//  Created by Still made by someone on 2016-03-18.
//  Copyright © 2016 :). All rights reserved.
//

#include "Text.hpp"

Text::Text(std::string __m_text, int x, int y, SDL_Renderer* renderer)
{
    m_text = __m_text;
    m_font = TTF_OpenFont("arial.ttf", 24);

    m_rect = new SDL_Rect();

    m_rect->x = x;
    m_rect->y = y;

    m_surface = TTF_RenderText_Solid(m_font, m_text.c_str(), m_color_fg);
    if (m_surface == nullptr)
    {
        std::cout << "Failed to create text surface : " << SDL_GetError() << std::endl;
    }

    m_texture = SDL_CreateTextureFromSurface(renderer, m_surface);
    if (m_texture == nullptr)
    {
        std::cout << "Failed to create text texture : " << SDL_GetError() << std::endl;
    }

    TTF_CloseFont(m_font);
    SDL_FreeSurface(m_surface);
}

void Text::Render(SDL_Renderer* renderer)
{
    SDL_RenderCopy(renderer, m_texture, NULL, m_rect);
}

void Text::Update(SDL_Renderer* renderer)
{
    // This part throws me a error and makes the game crash.

    std::cout << "1 : " << SDL_GetError() << std::endl;
    SDL_FreeSurface(m_surface);
    SDL_DestroyTexture(m_texture);

    std::cout << "2 : " << SDL_GetError() << std::endl;

    m_surface = TTF_RenderText_Solid(m_font, m_text.c_str(), m_color_fg);
    m_texture = SDL_CreateTextureFromSurface(renderer, m_surface);
}

void Text::SetText(std::string text, SDL_Renderer* renderer)
{
    m_text = text;
    Update(renderer);
}

void Text::Destroy()
{

}


texts: Seamless transition between planet and space

texts: I have been curious about how this kind of seamless transition from space to planet can be implemented. It would be nice if someone could explain this as I can't really wrap my head around the solution.


texts:
I'm looking at hosting my flash game on a site like Kongregate or NewGrounds, but with so many choices, I'm left wondering what are the pros & cons of the various options?

I'm interested in:

Reaching the biggest audience
Making some money (eg. I know that Kongregate shares ad revenue)
Other features/benefits of the site (eg integration APIs for high scores, micro payments, etc)


texts: Unity - Serializing a single property or UnityEngine.Object reference

texts:
When I call new SerializedObject(obj) where 'obj' is a UnityEngine.Object instance, as I understand it this is what it does:

Each serializable property of the object is traversed, and its sub-properties recursively.
If the property is a reference to a UnityEngine.Object, it serializes the reference, not the object (simply its GUID or instanceID).

However, what if I want to serialize a single property like a UnityEngine.Object reference?
There must be an internal method for serializing/deserializing values, but I don't know what it is or if there's possibly a better way.

This was brought about when I wanted to store a UnityEngine.Object reference as a string, so I could load it later on as an Object.
This got me thinking that the only way I could achieve this was to contain the reference within another UnityEngine.Object and serialize that, but this struck me as quite an odd approach.

I've also encountered an unusual scenario where I had a very complex and dense serializable object, but I only wanted a single SerializedProperty. The only way it seemed was to serialize the entire object, causing noticeable lag which could have been prevented were there a more appropriate method.

So... to phrase my question succinctly, how do I serialize a single property (including UnityEngine.Object refs) without using SerializedObject or EditorJSONUtility?


texts: How to make balls (water, or fluid) through pipe

texts:
I'm working on a project and get stuck for days. I want to make balls going through the pipe like this game:

You can watch this Youtube video for more detail.
How can i replicate this game machenis?


texts:
I am making a 2D platformer where the player has to reach the end of the level as fast as possible. I would like the player to be able to find new ways to reach the end of the level faster.

Making multiple path is not enough, in my opinion, because the shorter one will be easily findable and the others will become useless. I thought that maybe I should add abilities to the player to increase the number of possibilites.

I would like the player to be able to find strategies I have not thought about. For example players who are doing speedruns find new path and strategies to beat a game faster. I would like to help the research of new strategies. I would like to make new strategies possible even if I have not specificaly thought about them.

My question is, how can I make it possible for the player to make up new strategies ?


texts:
I want to try adding shadows to a 3D XNA game. I've set up some testing environment with one light and one camera. However, I'm running into artifacts with my approach.

I'm using the shader code from http://pastebin.com/zXi0hmsU to render the final result and http://pastebin.com/rY4Gcj9N to create the shadow maps. The code is pretty straight forward and involves production of the depthmap from the light point of view, then projecting it into the camera space and checking for occlusions.

However, from most angles I am getting pretty ugly results

The scene consists of some simple cubes (constructed by hand, facing outside, backface is culled), one light (shadow map shown in top left corner - looks okay) and one camera.

My RenderTarget for the shadow maps is initialized by

int shadowMapSize = 512;
RenderTarget2D shadowMap = new RenderTarget2D(GraphicsDevice, shadowMapSize,
    shadowMapSize, true, GraphicsDevice.PresentationParameters.BackBufferFormat,
    DepthFormat.Depth24Stencil8);
GraphicsDevice.SetRenderTarget(shadowMap);
GraphicsDevice.Clear(Color.White);
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

Afterwards, the CreateShadowMap effect is applied, followed by the LambertWithShadows effect. Finally, the shadow map is drawn using a SpriteBatch.

Rest of the code consists of simply providing the correct values to the shaders. If necessary, I can provide it at well.


texts: DirectX 11 - Problem with low resolution decals

texts:
I'm trying to add a decal system in my DirectX engine but i'm facing some problems with the quality of the textures projected. Every other no decal texture look fine, but these ones look really bad.

What I do in the shader is:

    float4 PSDecal(
    in float4 iPosition : SV_Position
    ) : SV_Target
{

    int3 ss_load_coords = uint3(iPosition.xy, 0);

    float3 wPos = txWorldPos.Load(ss_load_coords).xyz;

    float4 lightSpacePos = mul(float4(wPos,1), LightViewProjection);
    lightSpacePos.xyz /= lightSpacePos.w;
    lightSpacePos.x = (lightSpacePos.x + 1) * 0.5;
    lightSpacePos.y = (1 - lightSpacePos.y) * 0.5;

    float4 light_mask = txLightMask.Sample(samLightBlackBorder, lightSpacePos.xy);
    if (lightSpacePos.w < 0)
        light_mask.xyzw = .0;

    return light_mask;
}

Here you can see the result decal, the original texture and the projection space of the decal:

In the last image you can see there are noticeable artifacts, and thats why the resulting image gets distorted, but I don't understand why...

Also, I have the same problem when generating the light shadows, they get pixelated too. In this case, the shadow map is being calculated correctly, and it's not distorted.

Maybe it's the world position that is being loaded?


texts:
I'm working on implementing an RPG engine, and I'm trying to figure out the best way to implement equipment.  The really tricky part is the hand slots.

It would be easy to give a character one hand slot for a weapon, and one off-hand slot for a shield.  But defining it that way would make it impossible to dual-wield, or to wield two-handed weapons.  Giving the character two generic "hand slots" would allow for dual wielding, two-handed weapons is where things get tricky.

The obvious way to equip a two-handed weapon is by filling both slots with the same object. But then I need special-case code for calculating stat bonuses (you can't simply sum all bonuses from all slots, because the weapon's values will get added twice) and for removal (you can't just clear the item from one slot).  If I only put the object in one slot, then calculating bonuses becomes easy again, but there needs to be special-case code to check whether the "empty" offhand slot is really empty or not.

Obviously I'm not the first person to face something like this. Two-handed weapons have been around in RPGs for decades.  Is there any elegant way to handle the logic involved?


texts: unity how to make an animation reverse mid way through

texts:
I have a animation of several parts moving (think bridge) and would like the animation to reverse mid way through if a certain condition is modified (function call). I have the Animation and the AnimationClip which are added via a script.

Currently this is the code:

Animation anim;
public AnimationClip Open;
// Use this for initialization
void Start () {
    anim = GetComponent<Animation>();
    anim.AddClip (Open, "Open");
    anim.Play ("Open");

}
void Update(){
    Debug.Log ("update");
    if (Input.GetKeyDown ("space")) {
        rev ();
        Debug.Log("reversing");
    }
}
void rev(){
    anim.Rewind()

}

However anim.Rewind() doesn't do what I want it to do it moves the animation back the the first frame rather then slowly move the animation backwards. I know there are some tricks involving the time or by changing the speed but I cannot figure those out either.


texts: Character is out of location after animation montage in UE4

texts: so I have my running and idle animation working fine on my character but once I do the attack animation thru an animation montage, my character slowly floats off the ground and as I attack many times it floats more and more and sometimes starts to lean and when I run and Idle it stays on air .. attached link to video — https://www.facebook.com/groups/467991570685914/permalink/940206510131082/


texts: Unity Shadow shows on my Android device but NOT my Windows Mobile device

texts:
Unity version: 2017.1.1f1
Problem:
I'm using Directional Light. Shadow is not showing in my Windows Mobile device (Lumia 640 XL), but works fine when I run the exact same UWP project as PC (Local Machine) as well as Android.

Attempted solutions:
1) Quality Setting: I even removed the rest of levels and left only 1 level of quality.
2) Both soft and hard shadows, 10 Shadow distance, Stable Fit of shadow projection, very high resolution, low resolution, No Cascade.
3) Tried realtime and mixed light mode.

any idea? Thanks in advance for read my question.

Screenshots:
Windows 10 Mobile (Lumia 640 XL)

Android (Redmi Note 3)


texts:
In Unity the PhysicsManager has project data. It exists across scenes but its data is unique to each project. If it make my own CustomManager, where/how to I store its data so that it's associated with the project, not a particular scene.

Most of the examples show storing data in properties in components on GameObjects but the PhysicsManager is not a component of a GameObject as far as I can tell. I want my custom manager to do whatever PhysicsManager is doing to store its data.

Any examples, pointers, links to articles?


texts: Server Side : How to manage "delay" action/event like attacking?

texts:
at the moment I'm writing a game server, so I made an event "handler". I mean, if a player send to the server "I move" it fire a function, so I think I'm doing well at the moment.

But there's a problem and I don't know how to handle it. Lets take an example.

When a player want to attack he need to press a key one time, and it will attack automaticly every second, that means the server receive one packet with "I attack" and the server handle it, But I don't know how to make the player attacking every second correctly. It's kinda hard to explain I'm sorry ! So what I'm doing at the moment is, if the server receive from the player "I attack" I start a timer for the player which call a function every second. And I do that for every player but, I think that is not a nice idea. Should it be better to make one big timer ? If yes, which interval should I use ? 100ms or more ?

Well I hope you understood me, I know I didn't explain it well and sorry for that ! Thanks in advance for your help.


texts: How to prevent Dynamic Rigidbody2d with large mass pushing another Rigidbody2d into BoxCollider2D

texts:
I'm making a prototype for a game idea but hitting a problem :(
Quite new to Unity and feel like this should be relatively easy to solve, but keep going around in circles, and hoping to get some help :)
Video: https://gfycat.com/candidplushemeraldtreeskink
GameObjects:

Red box: has BoxCollider2D
Duck: has BoxCollider2D, Rigidbody2D (dynamic), some scripts
Wall: has BoxCollider2D, Rigidbody2D (dynamic), some scripts

Rules:

Red box: doesn't move, everything should stop when colliding with it
Duck: moveable by player, can't push "Wall"
Wall: moveable by player, can push "Duck"

To get "Wall can push Duck, but Duck can't push Wall" working, I set the Mass for Wall to be Infinity. However, this seems to have a side effect where Wall can now push Duck through Red box. Note: even increasing mass to something like 500 has this side effect too
If the mass for Wall is smaller, then it won't push Duck through Red box. However, with the smaller mass, Duck can then push Wall (which I don't want).
The script for moving Wall is:
private void FixedUpdate()
{
    // https://learn.unity.com/tutorial/world-interactions-blocking-movement?uv=2019.2&projectId=5c6166dbedbc2a0021b1bc7c#5ce3cdabedbc2a3ce61754e8
    Vector2 position = rigidbody2d.position;
    position.x += speed * horizontal * Time.deltaTime;
    position.y += speed * vertical * Time.deltaTime;
    rigidbody2d.MovePosition(position);
}

Question:

What should I do so "Wall can push Duck, but Duck can't push Wall" holds true, without Duck being pushed into the Red box.
Should I be using Dynamic Rigidbody (sort of physics with collisions and pushing), or Kinematic Rigidbody (and handle collisions and pushing manually)?

Thanks in advance!


texts: How to setup a client to work with a remote server or a local included server?

texts:
I'm working on a Networked multiplayer game, but while developing and for testing I want to set up a local server that acts like the multiplayer server.

My thought is to approach the server as a proxy setup. Creating a class that the client sees and essentially allowing it to either load the server code in itself or to use a networking layer.

Is this a good approach? Are there other approaches to look into?
What pitfalls should I be watching for?

Update

A bit more specifically I need to do this because I am targeting the Ouya and I can't guarantee a network connection, or even a spare machine to run the server on. And inside Android it is more difficult to setup and launch a service rather than include my server code right into a client build.


texts: Using System Time to compute delay times that correctly deal with app pauses?

texts:
In my Android app I have the requirement to introduce small (for slowing down animation) and larger delays (for the purpose of delaying the appearance of a character for example).

I've experimented with 2 different ways, those being:

long grabTime;
int delayInMillis;

public void doStuff(){

//Initialise timeGrab variable
    if (grabTime==0)
        grabTime = System.currentTimeMillis();

//Has the desired number of Milliseconds passed?
    if (System.currentTimeMillis()>timeGrab+delayInMillis)

//If so, then do something here

//And re-grab the time ready for the next time
    grabTime = System.currentTimeMillis();

}

Where I have a batch of sprites (where each one will have a different delay) I find it easier to do this

long grabTime;
int spritesDelay = new int[numberOfSprites];
int forLoopCounter;

//Populate the array with desired delays (in seconds)
spritesDealay[0]=1;
spritesDealay[1]=2;
spritesDealay[2]=3;
spritesDealay[3]=4;

public void doStuff(){

    //Initialise timeGrab variable
    if (grabTime==0)
        grabTime = System.currentTimeMillis();

    //Has 1 second second passed?
    if (System.currentTimeMillis()>(timeGrab+1000)){

    //If so, reduce delay counters by 1

    for (forLoopCounter = 0;forLoopCounter<spritesDelay.length;forLoopCounter++){

        spritesDelay[forLoopCounter]--;
    }

    //And re-grab the time ready for the next 1 second count
        grabTime = System.currentTimeMillis();
    }

    //Now run through all the sprites and check to see if any of the timers have expired

    for (forLoopCounter = 0;forLoopCounter<numberOfSprites;forLoopCounter++){

        if (spriteDelay[forLoopCounter]<=0){

    //Do stuff here

    //If action has completed then reset the delay

    if (*Some criteria has been met*){

    spriteDelay[forLoopCounter]=4; //put in either explicit value for all sprites or restore previously backed up spriteDelay array (Not shown here)

            }

        }

    }
}

In my app (a game) - I am using the second method to have some sprites moving in an up/down motion, each successive one with a slight delay on the previous one (think of a wave like motion).

The problem

This does work, however, when I pause my game (which simply halts game updates and continues rendering with a 'paused' graphic over the screen), on resuming play, things are out of sync slightly (because obviously the system time doesn't stop when the game is paused, so the first check after un-pausing to see if the second has elapsed will always be true providing the game was paused for longer than 1 second).

After the sprites have all moved through one motion, then they do sync up again and everything is OK.

However I'm not happy with the remainder of the current cycle being out of sync.

Alternatives?

Another way I've thought of doing this is hold an int that counts up each time my game update method is run (my game is 'limited' to 60 logic updates per second), then when it reaches 60, I would know a second has passed.  This has the advantage that the counting will stop when the game is paused.

However, if the game were ever to be run on a device that couldn't handle 60 logic updates per second then it would slow down counting and throw everything off.  (My ticks per seconds are separated from my rendering per second which runs flat out so although the FPS may drop, the logic updates per second should carry on at 60.  I find it unlikely that a device wouldn't be able to handle 60 game updates per second (as I've tested this on a Galaxy Ace version 1 and that was fine at 60) but I'd like my app to be as robust as possible and don't really want to risk the timings being thrown off by a slow device however unlikely.

So I'm a bit stuck.  Is there another system timer I can use which can be controlled?  (switched off when required) or would my 'logic-updates-per-second' method be the best bet?


texts: Outsourcing Artwork: Hourly or Per-Project?

texts:
I've hired people to produce art and graphics before, but only ever at a per-job rate and that has worked out well.

This question is for both artists and the people who hire them:

As a buyer, are there any situations or types of projects you've experienced where it worked out better billed at an hourly rate?

For artists, do you have a preference for one over the other and if so, why?


texts: Unity: Is type casting every frame too expensive?

texts:
I have a state machine that controls my enemy AI. Each AI has a target which may be a Player, an obstacle, a shell, or even a Vector2 position.

I'm trying to abstract my "target" member, and my first thought was to use GameObject, then downcast to whichever type I need for different enemies. Examples below:

class StateController: MonoBehavior {
    GameObject target;
    FireAction action;

    Update() {
        action.Fire(this);
    }
}

class FireAction: ScriptableObject {
    public abstract void Fire(StateController c);
}

//Examples of different fire scripts:
class FireAtPlayer: FireAction {
    public override void Fire(StateController c) {
        Player p = c.target as Player;
        //--use properties of Player object--
    }
}

class FireAtPoint: FireAction {
    public override void Fire(StateController c) {
        GameObject t = c.target as Player;
        //--use properties of GameObject object--
    }
}

As you can see, my Fire methods would cast the target object at every call to Update. Will this negatively affect my game's performance? Note that I know for a fact what type of object the target is, so I'm not guessing when I'm casting. Thank you in advance of your help!


texts: Facilitating XNA game deployments for non programmers

texts:
I'm currently working on an RPG, using the RPG starter kit from XNA as a base. (http://xbox.create.msdn.com/en-US/education/catalog/sample/roleplaying_game) I'm working with a small team (two designers and one music/sound artist), but I'm the only programmer. Currently, we're working with the following (unsustainable) system: the team creates new pics/sounds to add to the game, or they modify existing sounds/pics, then they commit their work to a repository, where we keep a current build of everything. (Code, images, sound, etc.) Every day or so, I create a new installer, reflecting the new images, code changes, and sound, and everyone installs it.

My issue is this: I want to create a system where the rest of the team can replace the combat sounds, for instance, and they can immediately see the changes, without having to wait for me to build. The way XNA's setup, if I publish, it encodes all of the image and sound files, so the team can't "hot swap." I can set up Microsoft VS on everyone's machine and show them how to quickly publish, but I wanted to know if there was a simpler way of doing this.

Has anyone come up against this when working with teams using XNA?


texts: Unity highlight/outline mesh edges/border (make them visible)

texts:
Let's say I create a cube using mesh triangles similar to the graph below. I would like to make those 12 edges visible in play mode so user/player can see them too (but without the diagonals).
What would be the best way to approach this problem in unity? Hundreds of cubes will be created in run time using mesh/triangles and the vertices position (vector3 value) will change at some point, so I am wondering if there's a way that allows those edges to change/move along when the mesh/triangles change and the edges still remain visible the whole time.
The desired outcome should be similar to the shaded wireframe in the scene view. Any help would be appreciated.


texts: Android loading screens blocking, good practice?

texts:
I've noticed many (if not all) android games don't support the "back" button functionality during their loading screens. Which leads to some frustrating moments when a user accidentally starts up the game and has to wait for the long loading stage to end in order to close it.

So my questions are:

1) Why is that ? Is there a good reason to avoid something like asynchronous loading (or some other solution to this problem) in android games ?

2) If there is no good reason not to support this functionality, what would be the best way to accomplish it ?


texts:
I'm trying to get the depth buffer for my 2D game working by offsetting the z value of the rectangles. For some reason, my depth buffer is coming back empty. The value is always 0. I'm assuiming there is something wrong with how I attach the depth buffer to the FBO? But I've looked over that code many times and don't see anything wrong with it. Let me know if you need more information.

I have depth testing enabled with GL_LEQUAL.
I have znear and zfar set to 1.f, -10.f and I have 9 quads setup at three different depths.
I have set glClearDepth(1.0) and I clear bot the COLOR_BUFFER_BIT and DEPTH_BUFFER_BIT before I draw to the FBO, however the value is still 0.

FBO setup:

RenderTarget::RenderTarget(int width, int height) {

    mWidth = width;
    mHeight = height;
    mVbo = 0;

    // Create the color buffer
    glGenTextures(1, &mTextureId);
    glBindTexture(GL_TEXTURE_2D, mTextureId);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

    // Create the depth buffer
    glGenTextures(1, &mDepth);
    glBindTexture(GL_TEXTURE_2D, mDepth);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, mWidth, mHeight, 0, GL_RED, GL_BYTE, NULL);

    /*glGenRenderbuffers(1, &mDepth);
    glBindRenderbuffer(GL_RENDERBUFFER, mDepth);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, mWidth, mHeight);*/

    // Create the frame buffer
    glGenFramebuffers(1, &mFbo);
    glBindFramebuffer(GL_FRAMEBUFFER, mFbo);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTextureId, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, mDepth, 0);

    GLenum err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    assert(err == GL_FRAMEBUFFER_COMPLETE);

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    createVbo();
}

Fragment shader

#version 120

uniform sampler2D diffuseMap;
uniform sampler2D lightmap;
uniform sampler2D depthMap;

varying vec4 texCoord[2];

void main()
{
    vec4 color = texture2D(diffuseMap, gl_TexCoord[0].st);
    vec4 light = texture2D(lightmap, gl_TexCoord[0].st);
    vec4 depth = texture2D(depthMap, gl_TexCoord[0].st);

    vec4 final = color * vec4(0.1);
    final += color * light;
    gl_FragColor= vec4(depth.r, depth.r, depth.r, 1.0);
}

Method to draw sprites to the screen/framebuffer

void GraphicsDevice::drawSprite(ISprite *sprite, float x, float y, float z, Material::TextureType type, Color c) {

    glActiveTexture(GL_TEXTURE0);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glBindBuffer(GL_ARRAY_BUFFER, sprite->getVbo());

    glBindTexture(GL_TEXTURE_2D, sprite->getMaterial()->getTexture(type)->getId());

    glPushMatrix();
    glTranslatef(x, y, z);
    glColor4f(c.r, c.g, c.b, c.a);

    glVertexPointer(3, GL_FLOAT, sizeof(Vertex), (void*)offsetof(Vertex, x));
    glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (void*)offsetof(Vertex, tx));

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glPopMatrix();

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

}


texts: Calculate smooth transition between local space angles

texts:
I'm trying to calculate direction of moving character (to rotate it's animation).
I have something like this:

Character can have 4 cardinal directions. The rotation is calculated from the current cardinal direction.
So for example For north we have -90 degrees from N to W and 90 degrees from N to E.
From E to N we have -90 degrees and from E to S we have 90 degrees.

The problem occurs when character is switching directions.It happens at about half the distance between cardinal directions. At this point current rotation is switching from negative to positive number (or other way around), and there is noticeable hitch. When for example going from E to N, it switches to N direction but it was at about -45 degrees which in N space it places for a frame or two between N and W directions.

Why do I calculate angles in cardinal direction space ? Animations are prepared for strafing or moving backward (or any other angle) and I need to assume that the direction of animation is 0 degrees and calculate from here.

Is there way to smoothly change angle between cardinal directions ?

For now I tried to lerping between them when switching (which improved overall look but is far from smooth transition), tried to  track from which direction the switch is coming, but it didn't really improved anything.

FVector Right = Character->GetActorRightVector();
FVector Forward = Character->GetActorForwardVector();
FTransform Transform = Character->GetTransform();
FVector CurrentAcceleration = CMC->GetCurrentAcceleration();
FVector CurrentVelocity = CMC->Velocity;

FVector AccelerationDirection = CurrentAcceleration.GetSafeNormal2D();
FVector VelocityDirection = CurrentVelocity.GetSafeNormal2D();

FVector LocalAcceleration = Transform.InverseTransformVectorNoScale(AccelerationDirection);
FVector LocalVelocity = Transform.InverseTransformVectorNoScale(VelocityDirection);

float DeltaTime = Output.AnimInstanceProxy->GetDeltaSeconds();

float Atan2Angle = FMath::Atan2(LocalVelocity.Y, LocalVelocity.X);
const int32 ChildIndex = FMath::RoundToInt((Atan2Angle * 2 / PI) + 4) % 4;

float VelAngle = FMath::RadiansToDegrees(VelQuat.GetAngle());
float OldOrient = CurrentOrient;

EFCardinalDirection Dir = static_cast<EFCardinalDirection>(ChildIndex);
EFCardinalDirection OldDir = static_cast<EFCardinalDirection>(OldDirection);

float DirDot = 0;
//main switch wihin which I determine from where calculate angle.
switch (Dir)
{
case EFCardinalDirection::N:
{
    FQuat ForwardQuat = FQuat::FindBetween(Forward, CurrentVelocity);
    float OrientN = FRotator(ForwardQuat).Yaw;
    CurrentOrient = OrientN;// FMath::FInterpConstantTo(OldOrient, OrientN, DeltaTime, 300.0f);
    break;
}
case EFCardinalDirection::E:
{
    FQuat LeftQuat = FQuat::FindBetween(Right, CurrentVelocity);
    float OrientE = FRotator(LeftQuat).Yaw;
    CurrentOrient = OrientE;// FMath::FInterpConstantTo(OldOrient, OrientE, DeltaTime, 300.0f);
    break;
}
case EFCardinalDirection::S:
{
    FQuat BackQuat = FQuat::FindBetween(Forward*(-1), CurrentVelocity);
    float OrientS = FRotator(BackQuat).Yaw;
    CurrentOrient = OrientS;
    break;
}
case EFCardinalDirection::W:
{
    FQuat RightQuat = FQuat::FindBetween(Right*(-1), CurrentVelocity);
    float OrientW = FRotator(RightQuat).Yaw;
    CurrentOrient = OrientW;// FMath::FInterpConstantTo(OldOrient, OrientW, DeltaTime, 300.0f);
    break;
}
default:
    break;
}


texts: Unity - Adressable - Build size is bigger than expected

texts:
After fixing all duplicates using Analyze tool, the apk file still bigger than before i start using Addressable.
All my bundle is local and use LZ4 compression.
Here what i have done:

Fix all duplicates found in "Check Duplicate Bundle Dependencies" by moving duplicate assets to appropriate groups.
Fix all duplicates found in "Check Scene to Addressable Duplicate Dependencies".
Fix all "Implicit" found in "Bundle Group Preview".

I use this Build Report Tool and see that non-addressable assets, scripts, dll is about 32MB and aa folder is around 110MB (i have nothing else in StreamingAssets folder) => the apk size should be around 140 - 150 MB but the apk size is 40MB bigger (188MB) :eek:
I suspect there're problem with compression. But have no idea how to fix this.
I extracted the apk and the total size is around 300MB. The non-addressable apk (~150MB)'s extracted size is ~500MB.
Any help is appreciated.


texts: Data structure for random outcome from a hit probability table

texts:
The basic idea of a hit-table is carried over from pen & paper role playing games. You roll a die or a number of dice representing your ability to attack an opponent. Your opponents defense is relative to your ability to attack: if you can roll higher than their defensive ability, then you hit them; if not, you miss.

Games started out with simple implementations and mechanics got more complicated as (e.g.) later editions of the rulebooks were published and players/customers desired a more realistic combat experience.

So conceptually, a hit table may look something like this:

Roll    Outcome
1-5     Miss
5-15    Dodge
16-20   Parry
21-80   Hit
81-100  Critical Hit

World of Warcraft calls this an attack table, but I haven't found a good resource which discusses a good data structure for this. The best implementation I have come up with so far is a linear traversal of an ordered list of the relative outcomes, which makes the decision algorithm O(n), where n is the number of possible outcomes.
The psuedo-code for this comes out to be:

var result = randome.next(0, hittable.maxvalue)
foreach outcome in hittable
    if result < outcome.max_value
        return outcome

// Reached the end of the table without finding an outcome
// Probably an error here, but let's fake it
return hittable.last

A typical combat in (most) modern games has many, many attacks that go to the hit-table for determination, as well as many possible outcomes. It is not hard to imagine this lookup becoming a serious bottleneck in terms of processing time. I remember the algorithm of a bucket sort from my Comp. Sci. coursework and have been enamored with the idea of finding a datastructure which would allow for a O(1) lookup of random number values. What would such a datastructure look like?

I can imagine how it could work with a one-liner query in SQL, but something tells me that would be adding a whole lot of overhead for a not-true O(1) solution.

SELECT name FROM hittable
WHERE hittable.min_roll < RAND() AND RAND() < hittable.max_roll

This is just a notion that popped into my head because "it's a hitTABLE, so why not store it in a table". Note: the above query also would not work because the two calls to rand would return random numbers.

Edit: MMORPGS have also implemented something similar for Loot Tables, which determines what you get from winning a battle (by looting the corpse of the defeated foe). This is complicated by having multiple potential outcomes for each random result, e.g.

Roll    Outcome
1-5     Nothing
5-15    Some Gold
16-20   An Item
21-80   Some Gold and An Item
81-100  Lots of Gold and TWO Items

In a game the size of World of Warcraft, you could have thousands of players looting the same monster in any given second, so again a strong argument can be made for finding the very fastest way to perform lookups of this manner.


texts: How to expose game data in the game without a singelton?

texts:
I'm quite new to cocos2d and games programming, and am currently I am writing a game that is currently in Prototype stage. Everything is going okay, but I've realized a potentially big problem and I am not sure how to solve it.

I am using a singelton to store a bunch of arrays for everything, a global list of planets, a global list of troops, a global list of products, etc.  And only now I'm realizing that all of this will be in memory and this is the wrong way to do it.

I am not storing files or anything on the disk just yet, with exception to a save/load state, which is a capture of everything.

My game makes use of a map which allows you to select a planet, then it will give you a breakdown of that planets troops and resources,

Lets use this scenario:

My game has 20 planets. On which you can have 20 troops.

Straight away that's an array of 400!

This does not add the NPC, which is another 10.

So, 20x10 = 200

So, now we have 600 all in arrays inside a Singelton.

This is obviously very bad, and very wrong.  Especially as the game scales in the amount of data.

But I need to expose pretty much everything, especially on the map page, and I am not sure how else to do it.

I've been told that I can use a controller for the map page which has the information I need for each planet, and other controllers for other items I require global display for.

I've also thought about storing each planet's data in a save file, using initWithCoder however there could be a boatload of files on the user's device?

I really don't want to use a database, mainly because I would need to translate NSObjects and non-NSObjects like CGRects and CGPoints and Colors into/from SQL.

I am open to other ideas on how to store and read game data to prevent using a singelton to store everything, everywhere.

Thanks for your time.


texts: Libgdx 2D Game, Random generated World of random size, how to get mouse coordinates?

texts:
I'm a noob and English is not my mothertongue, so please bear with me!

I'm generating a map for a Sidescroller out of a 2D-array. That is, the array holds different values and I create blocks based on that value.

Now, my problem is to match mouse coordinates on screen with the actual block the mouse is pointing at.

public class GameScreen implements Screen
{
    private static final int WIDTH = 100;
    private static final int HEIGHT = 70;

    private OrthographicCamera camera;
    private Rectangle glViewport;

    private Spritebatch spriteBatch;

    private Map map;
    private Block block;

...

@Override
public void show()
{
    camera = new OrthographicCamera(WIDTH, HEIGHT);
    camera.position.set(WIDTH/2, HEIGHT/2, 0);

    glViewport = new Rectangle(0, 0, WIDTH, HEIGHT);

    map = new Map(16384, 256);
    map.printTileMap(); // Debugging only

    spriteBatch = new SpriteBatch();
}

@Override
public void render(float delta)
{
    // Clear previous frame
    Gdx.gl.glClearColor(1, 1, 1, 1 );
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    GL30 gl = Gdx.graphics.getGL30();
//    gl.glViewport((int) glViewport.x, (int) glViewport.y, (int) glViewport.width, (int) glViewport.height);

    spriteBatch.setProjectionMatrix(camera.combined);
    camera.update();

    spriteBatch.begin();

    // Draw Map
    this.drawMap();

//    spriteBatch.flush();
    spriteBatch.end();
}

private void drawMap()
{
    for(int a = 0; a < map.getHeight(); a++)
    {
        // Bounds check (y)
        if(camera.position.y + camera.viewportHeight < a)// || camera.position.y - camera.viewportHeight > a)
            break;

        for(int b = 0; b < map.getWidth(); b++)
        {
            // Bounds check (x)
            if(camera.position.x + camera.viewportWidth < b)// || camera.position.x > b)
                break;

            // Dynamic rendering via BlockManager
            int id = map.getTileMap()[a][b];
            Block block = BlockManager.map.get(id);

            if(block != null) // Check if Air
            {
                block.setPosition(b, a);
                spriteBatch.draw(block.getTexture(), b, a, 1 ,1);
            }
        }
    }
}

As you can see, I don't use the viewport anywhere. Not sure if I need it somewhere down the road.

So, the map is 16384 blocks wide. One block is 16 pixels in size.

One of my naive approaches was this:

if(Gdx.input.isButtonPressed(Input.Buttons.LEFT))
{
    Vector3 mousePos = new Vector3();
    mousePos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
    camera.unproject(mousePos);

    System.out.println(Math.round(mousePos.x)); // *16); // Debugging
    // TODO: round
 //   map.getTileMap()[mousePos.x][mousePos.y] = 2; // Draw at mouse position

 }

I confused myself somewhere down the road I fear. What I want to do is, update the "block" (or rather the information in the Map/2D-Array) so that in the next render() there is another block. Basically drawing on the spriteBatch g

So if anyone could point me in the right direction this would be highly appreciated.
Thanks!


texts: How can I get the vector3's names to gameobject name?

texts:
void DrawBox()
    {
        SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color);
        SpawnLineGenerator(v3FrontTopRight, v3FrontBottomRight, color);
        SpawnLineGenerator(v3FrontBottomRight, v3FrontBottomLeft, color);
        SpawnLineGenerator(v3FrontBottomLeft, v3FrontTopLeft, color);

        SpawnLineGenerator(v3BackTopLeft, v3BackTopRight, color);
        SpawnLineGenerator(v3BackTopRight, v3BackBottomRight, color);
        SpawnLineGenerator(v3BackBottomRight, v3BackBottomLeft, color);
        SpawnLineGenerator(v3BackBottomLeft, v3BackTopLeft, color);

        SpawnLineGenerator(v3FrontTopLeft, v3BackTopLeft, color);
        SpawnLineGenerator(v3FrontTopRight, v3BackTopRight, color);
        SpawnLineGenerator(v3FrontBottomRight, v3BackBottomRight, color);
        SpawnLineGenerator(v3FrontBottomLeft, v3BackBottomLeft, color);
    }

And the gameobjects name:

    void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
    {
        GameObject myLine = new GameObject();
        myLine.name = start.ToString();

        myLine.transform.position = start;
        myLine.AddComponent<LineRenderer>();
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.endColor = color;
        lr.startWidth = 0.03f;
        lr.endWidth = 0.03f;
        lr.SetPosition(0, start);
        lr.SetPosition(1, end);
    }

The method SpawnLineGenerator get two vector3 and a color:

SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color);

In the SpawnLineGenerator i'm setting a name for each gameobject:

 myLine.name = start.ToString();

This give me the name for example: (-2.1, 3.4, 4.9)
Nut I want it be the name like this format:

v3FrontTopLeft (-2.1, 3.4, 4.9)
v3FrontTopRight (-1.1, 3.4, 4.9)

The problem is if there is a easy way to get the names v3FrontTopLeft and v3FrontTopRight and the rest from the method DrawBox instead typing each one.

I want to know that (-2.1, 3.4, 4.9) are the coordinates for v3FrontTopLeft


texts: MonoGame creates a copy of song files in XNBs location

texts:
I'm having a problem. I've been adding .wma files to the Content Pipeline app to be used as my game's background music. But today when I opened the solution/project/content/bin/music folder I spotted the following:

So am I forced to ship the .wma files with the actual XNBs when I distribute my game? No other asset gets copied like this so how do I prevent songs from being copied as well?

If I delete the .wma files manually then the next time I build the project they get automatically added again :/


texts:
I was wondering if the both shader codes are equivalent.
So the question is, is this GLSL

vNormal = mat3(FUSEE_ITMV[0].xyz, FUSEE_ITMV[1].xyz, FUSEE_ITMV[2].xyz) * fuNormal;

Equivalent to this HLSL?

float3x3 fMatrix = {FUSEE_ITMV[0].xyz,FUSEE_ITMV[1].xyz,FUSEE_ITMV[2].xyz};
output.normal = normalize(mul(input.normal,(float3x3)fMatrix));

Theoretical I'd say yes they are but I'm not sure. Can anyone verify that they are equivalent?


texts:
It's a blob shadow which is built in Unity's standard asset package.

As you see in the figure below, a shadow that is created by the Unity Projector is duplicated at the floor below.

How can I prevent this duplicated shadow?


texts: Browser sandbox for object interaction testing

texts:
I’m looking for a sandbox where I can upload/import STL or OBJ files (rigid bodies that I can export from a CAD software) for quick interaction testing with gravity and contact.

The idea is lowest friction possible for import/upload so that the time between file export from CAD software to testing of joints and such will be as quick as possible. So things like creating a sandbox template in Unity and then building the game every time would be out of the question.

Any ideas?


texts: How to get past Visual Studio "Setup Error" for Unity development?

texts:
When I launch Visual Studio from Unity on my laptop, I get the following error:

Setup Error
The setup for this installation of Visual Studio is not complete. Please run the Visual Studio Installer again to correct the issue.

As instructed, I've tried reinstalling Visual Studio multiple times, or using the "repair" option, but nothing has resolved the error.
How can I fix this?


texts:
Can a matrix be used when drawing lines and paths on android?

the DrawBitmap mathod takes a matrix as argument, I cannot find anything similar
when drawing lines.


texts:
Link:https://academo.org/demos/rotation-about-point/

    private bool isTiming = false;
    private float timeTillKeyIsPressed = 0;

    float time = 1;
    float time2 = 4;

    void Update()
    {
       if (isTiming)
        {
           if (timeTillKeyIsPressed <= time)  //0<=1 1<=1
            {
                if (time2 != 0) //4!=0 4!=1 4!=2 4!=3 4!=4
                {
                    time2 -= Time.deltaTime;

                    float angle = 360;   // reset here but not work properly

                    rb.transform.Rotate(Vector3.forward * angle * Time.deltaTime / time);

            }
        }
    }

    public void Rotate(float angle)
    {
        float d = angle * Time.deltaTime;

        int movement = GetMovement();

        rb.transform.Rotate(Vector3.forward * d * (float)movement * speed);

    }

  public int GetMovement()
  {
        if (Input.touchCount > 0)                              //mobile     //how many count touch
        {
            Touch touch = Input.GetTouch(0);

            float num = (float)(Screen.width / 2);

            var touchres = touch.position.x;
            //DebugPanel.Log("touchres", "touchres:" + touchres);

            var res = touchres > num;
            //DebugPanel.Log("res", "res" + res);

            if (res)//TRUE(Right)
            {

                return -1;
            }
            else//FALSE(Left)
            {

                return 1;
            }
        }
        else
        {
            return (int)Input.GetAxisRaw("Horizontal") * -1;     //pc
            //return 0;
        }
    }

  void OnTriggerEnter2D(Collider2D other)  //here my obstacle touch my player
    {
        foreach (Transform child in transform)
        {
            if (child.tag == "point")
            {
                isTiming = true;
            }
        }
    }

Image:

when I m playing the game:

I want the:

Player Image:

I want the when my player touches my obstacle then I want to reset the position of my player??

I hope my question is understood.


texts: I am trying my hand at android game development. I want to start with a simple 2D board game. What is the best way to draw a game board like the one in the image attacked below. The blue circles are points where the players can place objects.


texts:
I'm rendering mirrored geometry by flipping it's world matrix. Before rendering mirrored geometry I set CULL_FRONT rasterizer state (for normal geometry it's CULL_BACK). This works perfectly.

However, I've started implementing instancing and would like to instance mirrored and not mirrored geometry together. What's optimal way to do it?

So far I've considered:

CULL_NONE, but it has huge impact on shading performance
Geometry shader to flip triangles, but GS is generally slow

Is there any other option? I've found SV_IsFrontFace, but there's not much documentation about it. I would like to tell GPU in VS: Hey, this triangle should be flipped.


texts: Cache misses and usability in Entity Systems

texts:
Lately I have been researching and implementing an Entity System for my framework. I think I read most articles, reddits and questions about it that I could find, and so far I think I am grasping the idea well enough.

However, it raised some questions about overall C++ behavior, the language I implement the entity system in, as well as some usability issues.

So, one approach would be to store an array of components in the entity directly, which I didn't do because it ruins the cache locality when iterating through data. Because of this, I decided to have one array per component type, so all components of the same type are contiguous in memory, which should be the optimal solution for quick iteration.

But, when I am to iterate component arrays to do something with them from a system on an actual gameplay implementation, I notice that I almost always am working with two or more component types at once. For example, the render system uses the Transform and the Model component together to actually make a render call. My question is, since I am not iterating linearly one contiguous array at a time in these cases, am I immediately sacrificing the performance gains from allocating components this way? Is it a problem when I iterate, in C++, two different contiguous arrays and use data from both at each cycle?

Another thing that I wanted to ask about, is how one should keep references to components or entities, since the very nature of how the components are laid in memory, they can easily switch positions in the array or the array could be reallocated for expanding or shrinking, leaving my component pointers or handles invalid. How do you recommend to handle these cases, since I often find myself wanting to operate on transforms and other components every frame and if my handles or pointers are invalid, its quite messy to make lookups every frame.


texts: How to create a two-way teleport system?

texts:
I'm trying to create a two-way teleport system in which players can move into a teleport gameobject, and is then teleported to another linked teleport gameobject.

How I was planning to have it work was very simple. On the teleport gameobject's script, it would have a public property to the other teleport's transform in which to teleport the player to. In OnTriggerEnter, I simply set the entering's collider position to that of the linked teleport.

void OnTriggerEnter(Collider other) {
    other.transform.position = DestinationPoint.position;
}

However, when the player's position is changed, it triggers the OnTriggerEnter of the destination teleport, and thus the player gets stuck bouncing back and forth between the two points.

What's a good way to prevent this? Some less than ideal solutions I came up with is to offset the position that player teleports too slightly so that he doesn't cause OnTriggerEnter to be called at the destination portal, but I'd like to avoid that.


texts: What is the best way to draw a big 3D model

texts: I am currently using ModelMesh.Draw() to draw the each mesh of the model and thus the whole model. Note that my models are very heavy -- around 30MB of data, I think if there is any other way to draw the models which is more efficient then performance of my application will better.


texts: How can I render player movement on a 2d plane efficiently?

texts:
I'm prototyping a 2d HTML5 game with similar interaction to Diablo II. (See an older post of mine describing the interaction here: How can I imitate interaction and movement in Diablo II?)

I just got the player click-to-move system working using the Bresenham algorithm but I can't figure out how to efficiently render the player's avatar as he moves across the screen. By the time redraw() is called, the player has already finished moving to the target point. If I try to call redraw() more frequently (based on my game timer), there's incredible system lag and I don't even see the avatar image glide across the screen.

I have a game timer based off this awesome timer class: http://www.dailycoding.com/Posts/object_oriented_programming_with_javascript__timer_class.aspx

In the future, there will be multiple enemies chasing the player. Fast pace is essential to the experience.

What should I do?


texts: How can I use iteration to lead targets?

texts:
In my 2D game, I have stationary AI turrets firing constant speed bullets at moving targets.

So far I have used a quadratic solver technique to calculate where the turret should aim in advance of the target, which works well (see Algorithm to shoot at a target in a 3d game, Predicting enemy position in order to have an object lead its target).

But it occurs to me that an iterative technique might be more realistic (e.g. it should fire even when there is no exact solution), efficient and tunable - for example one could change the number of iterations to improve accuracy.

I thought I could calculate the current range and thus an initial (inaccurate) bullet flight time to target, then work out where the target would actually be by that time, then recalculate a more accurate range, then recalculate flight time, etc etc.

I think I am missing something obvious to do with the time term, but my aimpoint calculation does not currently converge after the significant initial correction in the first iteration:

import math

def aimpoint(iters, target_x, target_y, target_vel_x, target_vel_y, bullet_speed):

    aimpoint_x = target_x
    aimpoint_y = target_y
    range = math.sqrt(aimpoint_x**2 + aimpoint_y**2)
    time_to_target = range / bullet_speed
    time_delta = time_to_target
    n = 0

    while n <= iters:
        print "iteration:", n, "target:", "(", aimpoint_x, aimpoint_y, ")", "time_delta:", time_delta
        aimpoint_x += target_vel_x * time_delta
        aimpoint_y += target_vel_y * time_delta
        range = math.sqrt(aimpoint_x**2 + aimpoint_y**2)
        new_time_to_target = range / bullet_speed
        time_delta = new_time_to_target - time_to_target
        n += 1

aimpoint(iters=5, target_x=0, target_y=100, target_vel_x=1, target_vel_y=0, bullet_speed=100)


texts:
Is there a way to disable buffer swapping in LibGDX every time the "render" call of ApplicationListener returns? I mean - I'm looking on some way to be able to tell the framework if I want the buffers swapped each frame.

The Application interface doesn't expose any such method, neither it is possible using static Gdx.graphics reference.

Side note: please refrain from answers saying I shouldn't or something in this flavor - I know what I need and why I need it.


texts: Libgdx Networking (http requests) - Login

texts:
I am new to Networking and Databases,
but im trying to learn MySQL and HTTP Requests to create a
user Login for a game.

My goal is to let users create accounts and login to them etc (for Highscores etc). I discovered the Libgdx Net Module and also got my server running with MySQL, Apache and PHP.
I want to use php files to communicate with the Database on the Server.

But my question is (since there is not a big documention for libgdx Network Module):  Where and how can i learn how to create proper HTTP Requests in LibGDX and should i use JSON?   Just give me a hint how to start.

Thanks ;)


texts:
I am trying to collide an aircraft with a FBX tunnel model. I don't know how to create multiple bounding boxes for a tunnel. The tunnel is contains a single mesh. I tried using the triangle picking sample here http://xbox.create.msdn.com/en-US/education/catalog/sample/picking_triangle
I also created a bounding sphere around the tunnel to be able to detect if the aircraft is inside the tunnel. If the ship is inside the tunnel then I check the triangle & ray intersection. I also detect the intersection. I tried changing the rotation and position of the ship when intersection occurred but although I can detect the intersection ship passes through the tunnel surface mostly and my rotation doesn't work well.

I also tried to calculate ray & plane (here it is triangle) reflection as below:

            if (intersection < 0.4f)
            {
                Plane pickedTriangle = new Plane(vertex1, vertex2, vertex3);
                Vector3 reflectionVector = Vector3.Reflect(direction, pickedTriangle.Normal);
                newPosition = modelPosition + direction * gameSpeed * reflectionVector;
                newDirection = reflectionVector;
                tIntersected = true;
            }

As I see newPosition isn't calculated correctly.

My question is; how can I calculate a new position after a ray & plane intersection.

I think this causes the ship sometimes pass the tunnel surface sometimes.
If there is a better way to detect and calculate tunnel collision I'll appreciate it.

Thanks


texts: Enter Key press event detect from textbox - Unity3D - C#

texts: i am doing a project with Unity3D . in the interface there is a textbox. once user input some text and and press enter key then i want to read the text in text box. so please tell me how to  programmatically detect the key press event in unity3D - C# using MonoDeveloper.


texts: Development platform for 2D web and mobile games

texts:
Is there a game development platform -- similar to Torque, or Unity -- which can be used to deploy 2D games on the following platforms:

Web
iOs
Android
Xbox Live Arcade (Preferred but not required)

And which has an integrated or mature physics engine? Perhaps, even a built in editor?

I've looked at the following possibilities but I've found something missing in each one. Of course in each case I may be guilty of misconception.

Corona SDK (No web deployment, no windows support)
Torque 2D (No web deployment)
Flash + Flash Punk or Flixel (No native android deployment, and I'm not sure if it is stable on mobile platforms)
Unity + SpriteManager2 (Not really optimised for 2D games, and I haven't seen enough advanced 2D examples -- like say platformers -- to really have any confidence in using it for something like this)

Has anyone had any luck with this?


texts: Do you need to make a tileset for a platformer?

texts:
I've been tasked to make a platformer, I've never made a tiled game before, is this necessary?

I.e. can I just make different child classes of a Sprite class and add place them on the map, adding their own functionality?

I'm using html5 canvas and JS if that makes a difference.


texts: Is there any possible option where you can open a custom SpriteFont? Because I need to add to my game a font that is not in Windows already. I saw this page Custom Sprite Fonts and it's like I want it, but there's no explanation on how to do it...


texts: how to detect if a line is crossing another shape in javascript?

texts:
given the situation here

http://jsfiddle.net/h902cLpy/

is it possible to detect that a line going from A to B does cross another shape while A to C doesn't?


texts: How can I check if two lines (created with function love.graphics.line) are crossing themselves? I may use this ability to create procedural maps via graphs.


texts: XNA captures mouse clicks when the game doesn't have focus

texts:
If I alt-tab and do stuff outside of the game window, the game still captures mouse clicks (both left and right clicks).

The game doesn't "consume" the clicks, since they are also sent to the application that has the focus.

But it's rather annoying to hear a gunshot each time you click in your internet browser...

Also, the problem occurs even if the game is set to fullscreen.


texts: High Resolution Timer Options in Windows

texts:
I'd like to know what are my options for high resolution timer in Window. I want a timer with at least 1ms precision since I need it for a rhythm game. I'm using QueryPerformanceCounter now, but I read there are many problems I can have with it (variable clock due to laptop power consuption, intel speed stepping, multi-core sync gives negative times, etc).

I tried SDL_GetTicks() but I realized it is implemented using QPC in Windows. What other options do I have?

Thanks.


texts: How to add local multiplayer feature in a game using bluetooth?

texts:
I have developed a turn based game using android studio.I want to add local multiplayer feature to it. Don't need a detailed explanation, I need some idea about the following aspects:-

Do I need a thread for each client?

How can the server identify a client?(Which client device is sending the information or pressing a button)

I saw the code of bluetooth chat application. In that code, only two devices can communicate with one another. But my game has to be played with four players and I can't figure out a way to connect and communicate among four devices.


texts: How does a subpass dependency guarantee the layout transition of a swapchain image happens after presentation engine finish reading the very image?

texts:
I'm going through vulkan-tutorial:
https://vulkan-tutorial.com/Drawing_a_triangle/Drawing/Rendering_and_presentation
And I found something weired:

How does this subpass dependency guarantee the layout transition(from UNDEFINED to COLOR_ATTACHMENT_OPTIMAL)of swapchain image happens after present engine finish reading(or working on) this swapchain image?i.e.Layout transition of this swapchain image bewteen external and subpass0 guarantees to happen after the imageAvailableSemaphores is signaled.
I did find some explanations on this topics from this blog:
http://themaister.net/blog/2019/08/14/yet-another-blog-explaining-vulkan-synchronization/

External subpass dependencies Render passes in Vulkan have a concept
of EXTERNAL subpass dependencies. This is arguably the most
misunderstood aspect of Vulkan sync. I’d like to dedicate a section to
this, because too many developers are lured into using it in cases
where it’s not terribly useful and very likely to cause bugs.
The main purpose of external subpass dependencies is to deal with
initialLayout and finalLayout of an attachment reference. If
initialLayout != layout used in the first subpass, the render pass is
forced to perform a layout transition.
If you don’t specify anything else, that layout transition will wait
for nothing before it performs the transition. Or rather, the driver
will inject a dummy subpass dependency for you with srcStageMask =
TOP_OF_PIPE_BIT. This is not what you want since it’s almost certainly
going to be a race condition. You can set up a subpass dependency with
the appropriate srcStageMask and srcAcessMask. The external subpass
dependency is basically just a vkCmdPipelineBarrier injected for you
by the driver. The whole premise here is that it’s theoretically
better to do it this way because the driver has more information, but
this is questionable, at least on current hardware and drivers.
There is a very similar external subpass dependency setup for
finalLayout. If finalLayout differs from the last use in a subpass,
driver will transition into the final layout automatically. Here you
get to change dstStageMask/dstAccessMask. If you do nothing here, you
get BOTTOM_OF_PIPE/0, which can actually be just fine. A prime use
case here is swapchain images which have finalLayout =
PRESENT_SRC_KHR.
Essentially, you can ignore external subpass dependencies. Their added
complexity give very little gain. Render pass compatibility rules also
imply that if you change even minor things like which stages to wait
for, you need to create new pipelines! This is dumb, and will
hopefully be fixed at some point in the spec.
However, while the usefulness of external subpass dependencies is
questionable, they have some convenient use cases I’d like to go over:

Automatically transitioning swapchain images Typically, swapchain
images are always just used once per frame, and we can deal with all
synchronization using external subpass dependencies. We want
initialLayout = UNDEFINED, and finalLayout = PRESENT_SRC_KHR.
srcStageMask is COLOR_ATTACHMENT_OUTPUT which lets us link up with the
swapchain acquire semaphore. For this case, we will need an external
subpass dependency. For the finalLayout transition after the render
pass, we are fine with BOTTOM_OF_PIPE being used. We’re going to use
semaphores here anyways.
I also do this in Granite.


texts: I am making a RPG game and I am seeking a bit of information on how to grant players random rewards, such as game items, weapons, gold, etc... after defeating a monster, or a NPC of some kind. The items would be pre made and already existing. I am not sure on what is the best way to approach this kind of system. Any tips of advice will be appreciated on the matter.


texts:
I have developed a simple game using Phaser.  It's work perfect on ios webkit, but on android there is no sound.  What causes this problem on one platform but not the other?

We are using this code to load:

this.load.audio('game_audio', 'audio/bgm.mp3');

Playing:

this.music = this.add.audio('game_audio');
this.boom.play()


texts: Registering and (more importantly) Unregistering with Message Server

texts:
I've finally implemented an extendable message class and messageServer class.  The message class dynamically assigns a unique static ID to each derived message type (ex.  ObjectCreatedMessage might be assigned id = 1).  The actual message data is a member of the derived class.

Messages can be pushed to MessageServer class by upcasting to MessageBase*.

Systems (or anything) can subscribe to Message Server by passing a std::function to:

typedef std::function<void(MessageBase*)> Callback;
void registerCallback(int messageType, Callback callback);

When MessageServer is processing messages, it pops a message off the queue, checks the message type, then sends the message to each callback function registered to that type.

My Questions are:

Is this efficient?
How could I implement an "unregister" function?  std::functions can't be compared by equality.
What is a smart way to handle the callback failing? (perhaps the registered object went out of scope so the function pointer is undefined)


texts: Inconsistent accessibility: parameter type is less accessible than method

texts:
I have a level class in which I make a new turret. I give the turret the level class as parameter. So far so good.
Then in the Update function of the Turret I call a function Shoot(), which has that level parameter it got at the moment I created it.

But from that moment it gives the following error:

  Inconsistent accessibility: parameter type 'Space_Game.Level' is
  less accessible than method
  'Space_Game.GameObject.Shoot(Space_Game.Level, string)'

All I know it has something to do with not thr right protection level or something like that.

The level class:

    public Level(Game game, Viewport viewport)
    {
        _game = game;
        _viewport = viewport;
        _turret = new Turret(_game, "blue", this);
        _turret.SetPosition((_viewport.Width / 2).ToString(), (_viewport.Height / 2).ToString());
    }

The Turret Class:

        public Turret(Game game, String team, Level level)
        :base(game)
    {
        _team = team;
        _level = level;

        switch (_team)
        {
            case "blue":
                _texture = LoadResources._blue_turret.Texture;
                _rows = LoadResources._blue_turret.Rows;
                _columns = LoadResources._blue_turret.Columns;
                _maxFrameCounter = 10;
                break;
            default:
                break;
        }

        _frameCounter = 0;
        _currentFrame = 0;
        _currentFrameMultiplier = 1;
    }

    public override void Update()
    {
        base.Update();

        SetRotation();
        Shoot(_level, "turret");
    }

The Shoot Function (Which is in GameObject class. The Turret Class inherited the GameObject Class. (Am I saying that right?)):

protected void Shoot(Level level, String type)
    {
        MouseState mouse = Mouse.GetState();
        if (mouse.LeftButton == ButtonState.Pressed)
        {
            switch (_team)
            {
                case "blue":
                    switch (type)
                    {
                        case "turret":
                            TurretBullet _turretBullet = new TurretBullet(_game, _team);
                            level.AddProjectile(_turretBullet);
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    }


texts: How to resolve "Accessed None trying to read property" error?

texts:
Whenever I finish running the project, this error message appears:

  Blueprint Runtime Error: "Accessed None trying to read property
  jogador". Blueprint:  Jogador_BP_Anim Function:  Execute Ubergraph
  Jogador BP Anim Graph:  Transition Node:  Result

By clicking to know where the error is coming from, the program tells me this code:

This is the code I made to get the player reference (jogador/player Animation Blueprint):

This is basically for the transition code between animations, to receive information whether or not the player is jumping (jogador/player Blueprint):

Animations perform normally, so the error doesn't seem to compromise project execution, but why does it occur?

I looked at some links, but I don't know how to remove it.

https://forums.unrealengine.com/development-discussion/blueprint-visual-scripting/86607-accessed-none-trying-to-read-property


texts: Calculation of perpendicular distance to camera plane explanation

texts:
I am following this tutorial for a Wolfenstein 3D engine. https://lodev.org/cgtutor/raycasting.html

Here is the relevant image from the tutorial:

I cannot figure out how dividing by rayDirX or rayDirY causes the distance calculation to work. The explanation given is about halfway down the page, right above this text if you search for it: "Calculate distance projected on camera direction".


texts: How can I update data saved using PlayerPrefs when there is a new version of my Unity3D game?

texts:
I'm using PlayerPrefs to store the players' highscore on each level, but in the next version I'll change how scoring works.

For example, In the old version players could easily reach 250 points on a specific level, while in the new version it's difficult to reach even 50.

I would like to delete PlayerPrefs data which were saved during earlier versions, because scores that high would cause some issues in the newer version.
What is the best way to safely maintain compatibility of saved data between versions, but also be able to reset them if a new update requires it?
My current solution is that from now on I use new keys to store the data, for example by adding the current version to it.

For example, in version 2.0 the data that was originally saved with the key "score-Level8" would now be saved with "score-Level8-2.0".

This way the player's progression gets "reset" after an update, but the old saves remain until another game changer update comes, and I have to increase the version part of the key from 2.0 to 3.0.
This feels a bit error-prone and unprofessional.


texts:
I have been making a 2D visiblity algorithm by following this tutorial http://simblob.blogspot.se/2012/07/2d-visibility.html

I have managed to create the light vertices and it works fine when I draw it in a single color, but I want to use a shadow map to get "faded" lights like this:

Mine looks like this now:

where the blue dot is the light center and the green is the lighted area.

How can I "apply" a sprite to this like this one?

My code lies here: http://github.com/doodlemeat/bugfree-octo-sansa


texts:
Everywhere I read says I should fix the time step of my physics simulation, and interpolate the result to the actual frame rate of my graphics. This helps with simplicity, networking, reproducibility, numerical stability, etc.
But as I understand it, fixed time step guarantees between 1 and 2 Δt of input lag, because you have to calculate one step ahead in order to interpolate. If I use 90 Hz physics, it gives me an input lag of about 17 ms, on average.
Since I often see gaming enthusiasts talking about 1 ms input lag, 1 ms delay, and how that makes a difference, I wonder how fast-action games does it, and how they reduce the input lag using fixed time step.
Or they don't, and 1 ms delay is just marketing mumbo jumbo?


texts: Seek Steering Behavior with Target Direction for Group of Fighters

texts:
I am implementing steering algorithms with group management for spaceships (fighters). I select a leader and assign the target positions for the other spaceships based on the target position of the leader and an offset. This works well. But when my spaceships arrive they all have a different direction. I want them to keep to look in the same direction (target - start).

I also want to combine this behavior with a minimum turning radius that is based on the speed. The only idea I have is to calculate a path for each spaceship with an point before the target position, so the ships have some time left to turn into the right position. But I dont know if this is a good idea. I guess there will be a lot of rare cases where this can cause a problem.

So the question is, if anybody knows how to solve this problem and has some (simple code) or pseudocode for me or at least some good explanation.


texts: Will there be any more books in the Game Programming Gems series?

texts:
It's been more than three years now that the last Game Programming Gems book was published.
The official website isn't updated anymore, and this page of Mark DeLoura's website seems to imply that the series is over.

Was there ever an official statement about this? Was number 8 the last book?

The Game Programming Gems were one of the most (if not the most) important resource for me and probably thousands of developers around the globe, did the Internet kill them?


texts: How can I move objects pixel by pixel in the scene editor?

texts: I'm trying to find a way to move objects pixel-by-pixel(on my screen at least) in the scene editor. I tried a lot of different buttons but nothing seems to work, please tell me Unity has this functionality because doing it by mouse or by altering X and Y yourself is really tedious.


texts: How do modern game engines achieve real-time rendering vs Blender's "slow" rendering?

texts:
I'm new to both gamedev and Blender, and there's something I can't shake:

In Blender, a single render (even using the more advanced Cycles renderer) can take up to 45 seconds on my machine. But obviously, in a game, you can have amazing graphics, and so rendering is obviously happening continuously, multiple times a second in real-time.

So I'm also wondering what the disconnect is, regarding how "slow" Blender's renders seem to be, versus how game engines achieve real-time (or near real-time) rendering.


texts: Using "friend" classes in game development

texts:
Typically in C++ game development speed is valued over encapsulation, you therefore see a ton of publicly accessible class members which really shouldn't be public.

I seem to find in most cases that only a very select few clases really need to known the inner workings of another classes to the point of modifying or reading their private data.

Creating public getters/setters for this private data exposes things which really shouldn't be modified willy-nilly.

Would a compromise here be to use friend classes? or is there some drawback to friend classes I'm not seeing.


texts: Getting around limitations posed by float in space game

texts:
I'm working on a procedurally generated game set in outer space. As in the real world, the game universe will be pretty much 99% empty, with planets/stars/solar systems etc... being very far apart.

For example at the beginning of the game, you will pretty much be stuck in the solar system you spawn in, as even flying from planet to planet will take a very long time. Flying from one solar system to another will be theoretically possible, however it would take days of IRL time without obtaining the in-game equivalent of a warp-drive.

I realize with all the thousands of planets/stars etc... they can't all be updated 60 times per second, and I can deal with that. Let me describe my problem.

Okay, so lets say 1 meter is 16 pixels.

Earth diameter      =  12,756,000 meters
Earth diameter      = 204,096,000 pixels
Earth circumference = 640,861,440 pixels

Okay, that's... still arguably manageable. Obviously there wouldn't be an earth.png, it could be procedurally rendered. But it gets worse:

Distance from earth to sun =   149,600,000,000 meters
Distance from earth to sun = 2,393,600,000,000 pixels

So if we define earth as our arbitrary origin, and we travel to the sun in our ship:

int main()
{
    //        Distance to sun:
    //        2393600000000
    float X = 2383695718491;
    std::cout << X << "\n";

    X += 6;
    std::cout << X << "\n";
}

This outputs:

2.3837e+012
2.3837e+012

That's the correct amount of zeroes, but now over 4 million pixels of precision is lost, and that's a big deal. And of course, the distance to the sun is tiny compared to the distance to the nearest star.

For the purpose of the game universe, I will decrease the distances just to make travel a little less boring, but this is still clearly impossible by only using x and y variables.

How should I handle these huge distances?

UPDATE: Just to clarify, I realize that earth is unimaginably huge and there's no way I'd be able to fill it with meaningful content. GTA V's map is about 100 square miles, and that's less than .00000005% percent of earth's surface. So my planets will definitely be significantly smaller than this, however the issue with huge distances remains.


texts: C++ Entity Component System: Diverse Behaviours

texts:
I'm trying my hand at an action RPG kind of game and using a modified version of entityx from alecthomas, which is basically an Entity Component System. I have really big troubles with some of the stuff I want to implement, because I don't know how to put it in terms of Components. Here are some of the things I can't figure out:

Let's say I have entities that are supposed to represent actors and they have things like Health, Stamina, Mana, Attributes... How would I implement a timed buff/debuff system, without defeating the purpose of ECS? Each actor can be affected by multiple buffs at a time and the buffs could influence anything about them. A component can only hold so much data and I can't introduce a new component for each buff that needs to save different data.
If I had a Chain Lightning skill that I cast with an actor and it selects and damages enemy actors at random immediately, the game-logic processor would just dish out the damage and create an entity for the Lightning Effect with a RenderComponent. But the RenderComponent will only tell the render processor that it is Lightning, where does the data go that describes which enemies were hit? Most skill effects have some kind of parameter for their renderable parts like Source, Target, Intensity...

Both questions are based on the same problem: How do I represent things that can have diverse parameters in as few components as possible?


texts:
I have a procedural approach to the game loop that runs various classes.

it looks like this:

continue any in progress animations
check for used input
apply AI
move things
resolve events such as collisions
draw it all to screen

I have seen a lot of posts about how drawing should be running separately as fast as it can, possibly in another thread.

My problem is that if the drawing runs as fast as it, can what happens if it tried to draw while I'm still applying the AI or resolving a collision?  It could draw the wrong thing on screen.

This seems to be a well established idea so there must be an explanation to this problem as I just cant get my head around it. The only solution I have is to update the screen so fast that any errors like that get refreshed before we see them but that sounds hacky.

So how does this work / how would you implement it so that they are in sync but running at different speeds?


texts: Finding inspiration / help for making up (weapon) names

texts:
I'm really bad with words, especially with English words. Currently I'm struggling to make a good weapon names for my game, it needs to display the weapon functionality (weak/strong/fast/ballistic etc) correctly as well. For example the best weapon in a (futuristic) game cannot be called just with the name "Laser", it's just too boring, right?

Are there any tools, websites or anything that helps me finding good names for weapons? (or anything else similar).

I was thinking to use scientific names, but noticed that they are really hard to write, and they get very long, and I also lack information about science, I only know I could use the atomic sub-particles names in the weapons for example.

How do I get started with becoming good with making up names? (this could apply in generally to any naming problems).


texts: Is it possible to store assets used in a Unity game (2D or 3D) in the database? I think it is less efficient but want to have single source of truth and maybe have the game contact the database everytime it loads to get the new updates.