texts: How to sync game tick in peer to peer game?

texts:
I am making a 2-player iphone action game using a synchronization service (in this case Firebase). The service allows state syncing through the internet, but I have to execute all game logic on the phones.

I've read a bunch of game networking articles, and since I have no server, it seems like if I can get both phones to start the game at "exactly" the same time in realtime, I can adjust everything from there. (Planning on using a "tick" count on each phone, and sending the tick along with actions, then rewinding the simulation if necessary. The phones divide the game into halves to determine authority).

But how do you get remote clients to start a game tick at the same time?? It seems like this would be necessarily in lock step peer-to-peer, and something like it in FPS games.

The strategy I'm using now tries to have one client "guess" the other client's clock time, including ping time. If correct, they both start the game based on the guess (since for that message it was on).

a: sends a.localTime
b: receives message. Returns b.localTime, and dTime(a-b)
a: receives message. Returns a.localTime, and dTime(b-a)
b: receives message. If a.localTime + dTime(b-a) is very close to new b.localTime, send accept message.
b: starts game at: new b.localTime + 1 second
a: receives accept. Starts game at accepted a.localTime + dTime(b-a) + 1s

I made a little number counter thing to go with the tick, and they're just barely off. I can't see how this is possible though, since A "guessed" B's time, they should start at exactly the same time...

See anything wrong with my method? What's an easier way? I'm trying to avoid using a server if possible.


texts: Fragment Shader Code returns weird values

texts:
i've implemented a shader that produces a simple Radar Ping given a uniform time input. ShaderToy Proof of concept

Now i implemented this into my real Opengl GLFW GLAD C++ Core4.5Profile NVIDIA GTX960 environment and recieve only weird ouput when i use my own function call.

Why do i recieve such a weird output if i use a function call in opengl glsl?

PS: I have a feeling this has something to do with the precision and the call by value standards of glsl.

Thank you very much for any response, or even a hint where to look for help.

EDIT: The problem was as Kevin van der Velden described.

Result Images:

This is my shader Code:

    #version 330 core

    in vec2 v_TexCoord;
    out vec4 FragColor;

    uniform float u_time;

    // Generates a BnW Ping on normalized 2d coordinate system
    float RadarPing(in vec2 uv, in vec2 center,in  float innerTail,
                   in float frontierBorder, in float timeResetSeconds,
                   in float radarPingSpeed, in float fadeDistance,
                   in float currentTime)
    {
        vec2 diff = center-uv;
        float r = length(diff);
        float timeMod = mod(currentTime, timeResetSeconds) * radarPingSpeed;

        float circle;
        circle += smoothstep(timeMod - innerTail, timeMod, r) * smoothstep(timeMod + frontierBorder,timeMod, r);
        return circle;
    }

    void main()
    {
        //normalize coordinates
        vec2 uv = v_TexCoord; //move coordinates to 0..1
        uv = uv*2.; // translate to the center
        uv += vec2(-1.0, -1.0);
        //uv.x *= iResolution.x/iResolution.y; //correct the aspect ratio

        float color;
        // generate some radar pings
        float fadeDistance = 1.0;
        float resetTimeSec = 5.0;
        float radarPingSpeed = 0.3;
        vec2 greenPing = vec2(0.0, -1.0);

        //WITHOUT FUNCTION CALL
        //vec2 diff = greenPing-uv;
        //float r = length(diff);
        //float moduloTime = mod(u_time, resetTimeSec);
        //color = smoothstep(moduloTime - 0.25, moduloTime, r) * moduloTime + 0.025, moduloTime, r);

        //WITH FUNCTION CALL
        color += RadarPing(uv, greenPing, 0.25, 0.025,  radarPingSpeed, fadeDistance, u_time);

        //OUTPUT
        FragColor = vec4(color, color, color,1.0);
    }


texts: How can I visually see changes made to a scene since the last git commit

texts:
I'd like to see the changes made in a scene (.unity file) before I commit them to git.

I have looked into several GIT/Unity solutions but all of them are made for merging changes and not for showing a diff with last version.

The problem with scene files is that they use GUIDs that point to other assets and when I open a diff for a scene file I can't really make anything out of it.

For example:

Instead, I'd like to see something like this:

Is there anything existing that does this?


texts: When and why is a Pool class needed to hold objects?

texts:
I've been studying opengl es and an example I saw was using a "Pool" class to keep track of touch and keyboard events.

Could someone please explain how and why a pool class is needed. From what I was reading it had something to do with garbage collection and limiting the number of input classes that are made.

This all seems a little abstract to me, so if someone could please explain what is going on, I'd appreciate it, I'll pasted some code here:

    public Pool(PoolObjectFactory < T > factory, int maxSize) {
        this.factory = factory;
        this.maxSize = maxSize;
        this.freeObjects = new ArrayList < T > (maxSize);
    }

    public T newObject() {
        T object = null ;
        if (freeObjects.isEmpty())
            object = factory.createObject();
        else
            object = freeObjects.remove(freeObjects.size() - 1);
            return object;
    }

    public void free(T object) {
        if (freeObjects.size() < maxSize)
            freeObjects.add(object);
    }

    PoolObjectFactory <TouchEvent> factory = new PoolObjectFactory <TouchEvent> () {

    @Override
    public TouchEvent createObject() {
         return new TouchEvent();
    }

    Pool <TouchEvent> touchEventPool = new Pool <TouchEvent> (factory, 50);
    TouchEvent touchEvent = touchEventPool.newObject();
    . . . do something here . . .
    touchEventPool.free(touchEvent);

Thanks!


texts:
I have a float[][] array in my terrainFragmentShader to load render the biomes, however the code simply does not work. No errors are being cast and when I remove the code biomeMap[int(pass_textureCoordinates.x)][int(pass_textureCoordinates.y)] by either deleting that section or manually setting it, it loads the appropriate texture.

vec4 textureColour = texture(backgroundTexture, pass_textureCoordinates);

float c = biomeMap[int(pass_textureCoordinates.x)][int(pass_textureCoordinates.y)];

if(c < 0)
    textureColour = texture(sandTexture, pass_textureCoordinates);
else if(c < 32)
    textureColour = texture(stoneTexture, pass_textureCoordinates);

All three textures load just fine and are rendered when not using this method and the biomes are being properly loaded and initialized.

Loading:

public void loadBiomes(float[][] biomeMap) {
    for(int x = 0; x < Terrain.VERTEX_COUNT; x++) {
        for(int y = 0; y < Terrain.VERTEX_COUNT; y++) {
            super.loadFloat(location_biomeMap[x][y], biomeMap[x][y]);
        }
    }
}

Initializing:

    location_biomeMap = new int[Terrain.VERTEX_COUNT][Terrain.VERTEX_COUNT];
    for(int x = 0; x < Terrain.VERTEX_COUNT; x++) {
        for(int y = 0; y < Terrain.VERTEX_COUNT; y++) {
            location_biomeMap[x][y] = super.getUniformLocation("biomeMap[" + x + "][" + y + "]");
        }
    }

And finally here is the entire terrainFragmentShader:

#version 400 core

in vec2 pass_textureCoordinates;
in vec3 surfaceNormal;
in vec3 toLightVector;
in vec3 toCameraVector;
in int biomeSize;

out vec4 out_Color;

uniform sampler2D backgroundTexture;
uniform sampler2D sandTexture;
uniform sampler2D stoneTexture;

uniform vec3 lightColour;
uniform float shineDamper;
uniform float reflectivity;

uniform float biomeMap[128][128];

uniform float offsetX;
uniform float offsetZ;

const int levels = 32;

void main(void){

    vec4 textureColour = texture(backgroundTexture, pass_textureCoordinates);

    float c = biomeMap[int(pass_textureCoordinates.x)][int(pass_textureCoordinates.y)];

    if(c < 0)
        textureColour = texture(sandTexture, pass_textureCoordinates);
    else if(c < 32)
        textureColour = texture(stoneTexture, pass_textureCoordinates);

    vec3 unitNormal = normalize(surfaceNormal);
    vec3 unitLightVector = normalize(toLightVector);

    float nDotl = dot(unitNormal,unitLightVector);
    float brightness = max(nDotl, 0.25);

    vec3 unitVectorToCamera = normalize(toCameraVector);
    vec3 lightDirection = -unitLightVector;
    vec3 reflectedLightDirection = reflect(lightDirection, unitNormal);

    vec3 totalDiffuse = brightness * lightColour;

    out_Color = vec4(totalDiffuse,1.0) * textureColour;

}

Why isn't the biome not loading? Is it an issue in me not getting the appropriate [x][y] from the pass_textureCoordinates?


texts:
In the last days, I tried to learn the basics of Direct3D12, using some online resources and tutorials/demos.

After failing to run the demos,
I created a new project in Visual Studio 2015, added the necessary configurations and tried to get the basic initialization done. However, running that project, it fails at the same location, which is D3D12CreateDevice() (builds without any warnings/errors).

The return value I keep receiving is DXGI_NOT_SUPPORTED. I changed my code to enumerate through all adapters of the DXGIFactory, which ended up with the same result (the same applies to the warp adapter).

This is the part of the device creation:

bool created = false;

UINT i = 0;
ComPtr<IDXGIAdapter1> pAdapter;
HRESULT hr = S_OK;
while (SUCCEEDED(m_dxgiFactory->EnumAdapters1(i++, pAdapter.ReleaseAndGetAddressOf())))
{
    DXGI_ADAPTER_DESC1 desc = {};
    pAdapter->GetDesc1(&desc);
    if (SUCCEEDED((hr = D3D12CreateDevice(pAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_device)))))
    {
        created = true;
        pAdapter.ReleaseAndGetAddressOf();
        break;
    }
}
if (!created)
{
    ComPtr<IDXGIAdapter1> pWarpAdapter;
    CHK(m_dxgiFactory->EnumWarpAdapter(IID_PPV_ARGS(&pWarpAdapter)));

    CHK((hr = D3D12CreateDevice(
        pWarpAdapter.Get(),
        D3D_FEATURE_LEVEL_11_0,
        IID_PPV_ARGS(&m_device)
        )));
}

My system is running on Windows 10, 64 bit and has integrated Intel HD Graphics, as well as a NVIDIA GeForce GT540M, using the Optimus Technology. I did make appropriate changes to the NVIDIA Control Panel, to make the program run on the GeForce 540M, which - according to the Control Panel - supports the DX12 Runtime and feature level 11.0.
The integrated card however, only supports DX11. According GPU-Z, the Intel card only supports DX10 and the GeForce DX11.

I did install all the latest Windows Updates and drivers for both cards.
My guess is, that this is a driver related problem, since I am not able to run the demos either.

Can this be any issue related to the program itself, or should I try to get help from NVIDIA(or Microsoft?) about this problem?


texts: Lighting, shader and GI is messing up the materials in Unity3D

texts: Hello Guys I am not very sound with Unity3D Lightmapping. Currently I have a set of low poly items in my scene. Textures on my models are getting washed out. They totally look absurd. here is a picture of expected (Right) vs current result (left)


texts: How can I efficiently store Vertex data in C#/XNA?

texts:
I am creating a terrain system using voxels in a somewhat minecraft-like style and I was wondering if there was anything I could do to increase the number of vertices I am able to store (and therefore render).

Based on different suggestions I have read I created a number of "chunks" of size 32x32x32 cubes and all of the vertices for these cubes are pre-calculated and stored in a VertexBuffer. I then have 7x7x7 of these creating a larger map. Therefore this is around 11 million cubes.

I was unable to render all 11 million cubes, so I removed any vertex in the buffer which would be completely hidden by an adjacent block (this removes all the interior/invisible surfaces/vertices). Overall this reduced the number of vertices by a factor of 36 in the simplified terrain example I am using!

However, this appears to be the absolute limit on the number of blocks I can render. This already takes about 1 GB of RAM according to the task manager (although the vertices themselves are closer to half of this - GC and all).

Do I have to simplify my terrain and/or accept this limit, or is there a better way to do this? I previously tried using instancing but that slowed down after only 20,000 cubes or so.

Thanks.


texts: How can I synchronize ocean waves over the network?

texts:
I've been performing a little bit of research in my spare time on ways to increase the interactivity of environments in a networked game or simulation.

One of my areas of research is fluid-dynamics and whether it would be possible to synchronize it over the network. I believe the short answer to that is - Yes of course you can. But there will obviously be trade-offs as there are with any network synchronization problem.

I was recently playing Battlefield 4 and a number of their maps have playable ocean areas with fully functional waves large enough to obscure entire boats during gameplay. It seems to work quite well as well.

My assumption here is that the ocean simulation is completely offline and each client performs synchronization with the server during initialization. This would allow all clients to run the exact same ocean simulation that appears to be dynamic but is in fact the same offline simulation every time.

Interaction with the ocean simulation appears to be only superficial with local splash/wave depression. I assume that is entirely local to the client and not synchronized.

My question here is:

Would the above be an appropriate way to synchronize fluid simulation over a networked game? If not, what would you suggest?


texts: Why isn't my method an option for onClick?

texts:
Update: The problem went away when I restarted Unity and tried again.

The problem

I am using Unity 2019.1.8f1 Personal with Visual Studio for Mac 7.8.4. I have a button named Refresh; I would like its onClick handler to be the public instance method Refresh() in the class Libretto. My GameView has the Libretto script as a component:

The script Libretto.cs includes:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Assertions;

public class Libretto : MonoBehaviour, IInputHandler
{

    // Other members omitted

    public void Refresh()
    {
        // Code omitted
    }
}

My scene Scene_Libretto has a Canvas that contains a Button named Refresh:

In the onClick() section of the Refresh component, I selected GameView, which is a GameObject:

When I try setting the function, the method Libretto.Refresh() is not an option:

Attempted solutions

Searching online, I have found these solutions, none of which work for me:

The method must be public. (It is.)
The method must be void with 0 or 1 parameters. (It is void with 0 parameters.)
The script should contain using UnityEngine.UI; (It does.)
Try creating a new object with just the script and use that. (This makes no difference.)
Your code must compile with no errors. (It does.)

Full project

I have tried to make my question complete, but, if anyone wants to look at my code, it is available on GitHub in espertus/UnityWordGames (a fork of Roger Engelbert's code from his book Word Games With Unity).

A sibling scene, Scene_Crossing, in the same project has a similar Refresh button and Refresh() method that work properly.

Update

It worked after I restarted Unity.


texts: The tile cursor is not on the same tile I selected

texts:
Here is the image, when I select the tile I want to paint, it paints in the correct box where I want it to be but the white cursor should also be in the same box but it is 2 units to the left? This really  makes it difficult to paint the tiles. I'm a beginner in unity and can't seem to fix this problem :(
Thank you for your help!


texts:
I am getting error code GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT when creating framebuffer on Mac (using glCheckFramebufferStatus).

I am using same code for rendering on Mac and iOS both. Maybe problem is in the buffers initialization. On iOS I am doing it this way:

    CAEAGLLayer* eaglLayer = (CAEAGLLayer*) super.layer;
    eaglLayer.opaque = YES;

    EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
    m_context = [[EAGLContext alloc] initWithAPI:api];

    if (!m_context) {
        [self release];
        return nil;
    }

    if (!m_context || ![EAGLContext setCurrentContext:m_context]) {
        [self release];
        return nil;
    }

    [self layoutIfNeeded];

    NSLog(@"Using OpenGL ES 2.0");

    [m_context
        renderbufferStorage:GL_RENDERBUFFER
        fromDrawable: eaglLayer];

Variable m_context is object EAGLContext

On the Mac this way:

NSOpenGLPixelFormat *nsglFormat;

NSOpenGLPixelFormatAttribute attr[] =
{
    NSOpenGLPFADoubleBuffer,
    NSOpenGLPFAAccelerated,
    NSOpenGLPFAColorSize, m_colorBits, //16
    NSOpenGLPFADepthSize, m_depthBits, //16
    0
};

[self setPostsFrameChangedNotifications: YES];

///< Next, initialize the NSOpenGLPixelFormat itself
nsglFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr];

///< Check for errors in the creation of the NSOpenGLPixelFormat
if(!nsglFormat) {
    NSLog(@"Invalid format... terminating.");
    return nil;
}

///< Now create the the CocoaGL instance, using initial frame and the NSOpenGLPixelFormat
self = [super initWithFrame:frame pixelFormat:nsglFormat];
[nsglFormat release];

///< If there was an error, we again should probably send an error message to the user
if(!self) {
    NSLog(@"Self not created... terminating.");
    return nil;
}

///< Now  set this context to the current context

[[self openGLContext] makeCurrentContext];

Maybe I am doing anything wrong when I initialize NSOpenGLContext. Can you see any error? Thankyou
UPDATE: Initialization of the OpenGL I am doing this way:

int m_width, m_height;

glGetRenderbufferParameteriv(GL_RENDERBUFFER,
                             GL_RENDERBUFFER_WIDTH, &m_width);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
                             GL_RENDERBUFFER_HEIGHT, &m_height);

// Create the depth buffer.
glGenRenderbuffers(1, &m_depthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_depthRenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER,
                      GL_DEPTH_COMPONENT16,
                      m_width,
                      m_height);

// Create the framebuffer object; attach the depth and color buffers.
glGenFramebuffers(1, &m_framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
                          GL_COLOR_ATTACHMENT0,
                          GL_RENDERBUFFER,
                          m_colorRenderbuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
                          GL_DEPTH_ATTACHMENT,
                          GL_RENDERBUFFER,
                          m_depthRenderbuffer);

// Bind the color buffer for rendering.
glBindRenderbuffer(GL_RENDERBUFFER, m_colorRenderbuffer);

// Set up some GL state.
glViewport(0, 0, 640, 480);
glEnable(GL_DEPTH_TEST);


texts: I'm having trouble with collision detection in XNA

texts:
I've written a tile editor and game in XNA, with velocities and gravity, and am having trouble with some of my collision detection things. It works okay, but seems to glitch between just inside and outside the tile the player is on. Here's my collision detection function and the other functions it uses:

void SolveCollisions(List<Tile> tiles, Vector2 screensize)
    {
        if (position.X < 0)
        {
            position.X = 0;
        }
        if (position.X + 32 > screensize.X)
        {
            position.X = screensize.X - 32;
        }
        if (position.Y < 0)
        {
            position.Y = 0;
        }
        if (position.Y + 32 > screensize.Y)
        {
            position.Y = screensize.Y - 32;
        }

        foreach (Tile t in tiles)
        {
            if (absTilePos(position.X) == absTilePos(t.position.X))
            {
                if (intersect(position.Y, t.position.Y, 32, 32))
                {
                    if (position.Y > 0)
                    {
                        velocity.Y = 0;
                        position.Y = tilePos(position.Y);
                    }

                    if (position.Y < 0)
                    {
                        velocity.Y = 0;
                        position.Y = tilePos(position.Y) + 32;
                    }
                }
            }

            if (absTilePos(position.Y) == absTilePos(t.position.Y))
            {
                if (intersect(position.X, t.position.X, 32, 32))
                {
                    if (position.X > 0)
                    {
                        velocity.X = 0;
                        position.X = tilePos(position.X);
                    }
                    if (position.X < 0)
                    {
                        velocity.X = 0;
                        position.X = tilePos(position.X) + 32;
                    }
                }
            }
        }
    }

    bool intersect(float p1, float p2, float s1, float s2)
    {
        if (p1 < p2 && p1 + s1 > p2)
        {
            return true;
        }
        if (p2 < p1 && p2 + s2 > p1)
        {
            return true;
        }

        return false;
    }

    float tilePos(float f)
    {
        int i = (int)f;
        i /= 32;
        i *= 32;
        return (float)i;
    }

    float absTilePos(float f)
    {
        int i = (int)f;
        i /= 32;
        return (float)i;
    }

The player also glitches into blocks on it's top and right ( http://puu.sh/2cVQf ) when it hits them instead of bouncing off them - it just goes straight into them.

Does anyone know how to remedy this? Thanks!


texts: Can't figure out how to create texture from a font-surface

texts:
I can't seem to be able to render my font, it crashes and I can't figure out why. It seems to load the font correctly, but the parts relating to surface crashes.

Why does my texture crash?

Here is the code bits relating to it. SDL2 and TTF has been initialized properly.

        TTF_Font *arial;
        SDL_Color mm_txt_color = {255, 255, 255, 0};
        SDL_Texture *myTexture;
        SDL_Rect myRect;
        load_font(MM_FONT_ARIAL, 18,  &arial);

        get_text_and_rect(0, 0, "Exit", arial, &myTexture, &myRect);

int load_font(char *filepath, int size, TTF_Font **font)
{
    (*font) == TTF_OpenFont(filepath, size);
    if((*font) == NULL ) {
        printf("ERROR: Failed to load font: %s.\n", filepath);
        return FAILURE;
    }
    return SUCCESS;
}

    void get_text_and_rect(int x, int y, char *text, TTF_Font *font,
        SDL_Texture **texture, SDL_Rect *rect)
    {
        int text_width;
        int text_height;
        SDL_Surface *surface;
        SDL_Color textColor = {255, 255, 255, 0};

        surface = TTF_RenderText_Solid(font, text, textColor);
        *texture = SDL_CreateTextureFromSurface(renderer, surface);
        text_width = surface->w;
        text_height = surface->h;
        SDL_FreeSurface(surface);
        rect->x = x;
        rect->y = y;
        rect->w = text_width;
        rect->h = text_height;
    }


texts: How to fix problems with connecting VsCode to Omnisharp server?

texts: I'm using sourcetree for version controlling for Unity. I'm using VsCode version 1.45.1 and when sourctree is running on pc and I open a script on my Unity project, VsCode can't connect to Omnisharp server. What's the problem? I've recently installed Git on my pc.


texts:
I can't find working solution for this problem anywhere. Here is what I'm trying to do:

My Android game contains 10+ levels, user quits game on level 2. Next time user starts game it load level 2 automatically. Thats all I want, no need to save objects, just load last scene. I prefer simple javascript, but examples on the unity tutorials confuse me. Thanks for answers.


texts:
I want to teach game development to kids as part of a course (year-long) involving Ruby.  Unfortunately it looks like the game development kits available in Ruby (even in the form of bindings) are pretty limited.

Is the best solution to go with JRuby and use jMonkeyEngine through the JVM?  I'd love to have the kids play with creating very basic 3d games.  Is there another better solution for Ruby or on the JVM through JRuby?

Average age of kids is probably 9 to 12, with some as young as 5 and as old as 18.


texts: How to transition between "rooms" / virtual cameras on a button press?

texts:
I'm trying to make a game that navigates like the example here:

I'd like it so that after combat, the player can push the button corresponding with an exit (left, right, up, down) and navigate like in this game.

Also I eventually hope to randomize each run of the game so it would hopefully have some flexibility outside of being hard baked.

I've seen examples of it being done with a player object and a collider, but the player won't actually be moving their character. I like this style of navigation because I think it still provides the joy of exploration for the player, but is more friendly of a navigation system for a novice like me.

How would I implement something like this?


texts: How can i put a skybox on a new layer with a new camera and then move the skybox?

texts:
I want to create a moving start effect. For example the space station is moving around the star or moving to the star. But instead moving the space station i think it will be better to make effect of the skybox moving.

I have in the Hierarchy a RigiBbodyFPSController and a child MainCamera.
Now i added a new Camera to the Hierarchy.

Now how do i make the rest  ? Moving the new camera and the skybox to new layer and move the skybox ? Or it's more logic to say to move the new camera that the skybox is with in it in the new layer.

Not sure if my idea is logic or if there are a better ways to do it.
The general idea is to make movement effect like the space station is moving around the star or to the star. Star i mean the skybox.

The skybox is on the right.
I can't see the skybox in the scene view i see it only when running the game in the game view.

This is a screenshot when the game is running then i can see the skybox in scene view and game view:


texts:
I'm working on a game that you control a trebuchet to throw balls to the opponent.

It's like a game called 'Medieval Siege'.  When the trebuchet is swinging its arm, player need to seize the best moment to press button and release the ball. Then the ball will fly at the tangent angle.

My problem right now is that the trebuchet arm swing too fast for player to seize the right moment. Meanwhile it has to be this fast otherwise it can't throw far enough. And there is a tiny string connecting the ball and trebuchet arm, if the arm swing too slow, the ball is just hanging on the string when the arm move.

I solve the problem by toggling step size, whenever the arm is swing, I change step size from 1/60 to 1/200. And once player release the ball, it's back to 1/60.

This works pretty good except my game is for multiplayer with networking. So changing step may cause problem.

Another solution I can think of is to allow it swing slow, but when player release the ball, I manually add velocity onto the ball while keeping its direction. I don't really like this solution cause it looks fake and I still have the problem that the ball is just hanging on the string, unless I make string very very short..

Please shed some light on this, thanks!

EDIT

Thanks for everyone's input, I solve the problem by making the arm swing slow and when player release the ball, grab ball's velocity and times two. It looks exactly the same as changing step size. There's just one extra thing I need to do. Because the arm is swinging really slow, the ball is just hanging on the arm end instead of swinging. I solved this by applying a force equal to the gravitational force on the ball during and only during the swing period. Then it no longer hang there but swing together with arm.

@MrCranky 's answer is detailed and looks doable, so I'd accept it. :)


texts:
For Unity AudioSource objects, what is the difference between the Play and PlayOneShot methods, besides their method signatures?

Is it simply that PlayOneShot won't stop an already playing sound from the AudioSource? So given a scenario where you can guarantee that a call to AudioSource.Play() won't occur again until its isPlaying boolean value is false, is there any reason to use PlayOneShot?


texts:
How to develop and optimize the illusion of meaningful character development between the player and NPCs?

It's very hard for a game developer to create unlimited dialogue options for just one NPC for the player to interact with, and develop some type of meaningful relationship with. Instead most developers create the illusion of choice in order to minimize the amount of dialogue an NPC has, yet maximize the player's illusion of meaningful development with that NPC.

I am pondering the idea of creating a Skyrim Mod that implements a clever way of reusing pre-spoken dialogue of all NPCs and to create the opportunity for the player to interact with the NPCs and create an illusion that the player makes meaningful dialogue choices to develop some type of relationship with NPCs later imposing consequences on the either player, the NPC, or both later in the game.

I am not asking of a way to create new dialogue, but rather how to cleverly reuse dialogue to achieve the same effect for different and new events. This is not just specific to Skyrim. The same ideas can still be useful for games under current development.

The illusion of choice is a very difficult concept to think about. A web series titled Extra Credits provides an excellent definition for this. For convenience I have copied very important terminology from Extra Credit that will help fortify answers to this game development question.

What is agency?

to have some control of an outcome

What is choice?

any moment during play that the player could perform 2 or more distinct actions but has to pick some number of actions less than the total number available to execute

What is consequence?

making you realize the impact of something you did

What is the difference between choice and consequence?

choice makes you think about what actions you will take, yet consequence makes you think about actions you have already taken

What is meaningful choice?

when the decision making process isn't arbitrary, when the player understands the choice their making and has some system to weigh their options, this does not by any means mean they have to fully understand what the consequences of each option will be only that they believe they have what the need to weigh the choices presented to them
meaningful choice is not a logical calculation with a definitive answer

What is illusion of choice?

any moment in a game where you as a player feel as though you're making a choice when in reality theres either no alternative option actually being presented or the consequences of that choice are negligible
players hate it when they notice the illusion of choice


texts:
Is there any way to get the source code of Minecraft servers? I tried decompiling but I get very obfuscated arguments, classes, and methods.

If the answer is no, how did services like Bukkit and Spigot create their 'servers'?


texts:
I've been using Adobe Flash and its keyframe-based animation for some years.
I recently about heard morph-targets animation from Wikipedia.

It seems that the morph target animation is also keyframe-based.
What are the differences between Flash's animation and morph target animation?


texts: Physics - Determine how much thrust to apply at each thruster for linear/angular acceleration

texts:
I have a question somewhat similar to this one: 2D Spaceship Thruster Movement - Turning.

I have a ship with thrusters placed randomly on it (not necessarily symmetrically), and I need to know which thrusters and how much to fire them to have a perfectly linear acceleration, as well as how much they contribute to the angular acceleration of the ship to know which ones to fire when you want to turn the ship.

What I know: the position and orientation of the thrusters, the center of mass of the ship.

Basically I just need a way to make the ship obey the commands as best as physically possible, the commands being 'move' (apply acceleration on thrusters so if results in a linear acceleration), and 'rotate' (apply differential acceleration to maximize angular and minimize linear acceleration).

The game is 2D.

Thank you very much in advance.


texts: GameObject with Audio File called with FindGameObjectWithTag returns "Object reference not set to an instance of an object"

texts:
I'm puzzled with this error because in a different file (see below), I'm doing exact same process to an object to enable/disable and works fine. But this new object throws the error, the object has a Script calling an audio file.
Enabling manually the Object, and playing the game the audio is fine. I hit the check box to disable it and I get the error "Object reference ..."
This audio object is attached to another GameObject which is the character of the game.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

    [RequireComponent(typeof(BoxCollider2D))]
    public class carController : MonoBehaviour {

        public float carSpeed;
        public float maxPos = 4.17f;

        Vector3 position;

        public ParticleHit pr;
        public AudioManager cr;
        public Blast cb;

                audioObj = GameObject.FindGameObjectWithTag("policeAuTag");
                audioObj.SetActive (true);
                cr.carSound.Play ();

What am I doing wrong.?
I have closed and reopened unity but nothing. I have changed the tag name but same error.

I have tried also "FindWithTag" and doesn't work.

What is causing the code to throw errors?


texts:
I implemented chartboost in my ios game and locally it wors great.

I can receive ads.

Now my game is online but in the google analytics I get only error messages from
the game, meaning the chartboost ads fail to load.

Here:
https://www.dropbox.com/s/cft98lk27mt7p3s/cb.jpg?dl=0

The iage show google analytics registering only failed loads and
there is no single successfull ad load?

What could be the problem here?


texts: Move object to mouse direction without raycast?

texts:
I have script moving object to mouse postion using raycast. But what I need now is use the mouse movement to move my object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HoverPanel : MonoBehaviour
{

public GameObject ground;
private Rigidbody rg;
public float moveForce, speed = 2;
public Vector3 Mouse_pos;

void Start()
{
    rg = gameObject.GetComponent<Rigidbody>();
}

void Update()
{

    rg.AddForce(Input.GetAxis("Vertical") * moveForce * ground.transform.forward);

    if (Input.GetAxis("Mouse X") < 0)
    {
        //Code for action on mouse moving left
        print("Mouse moved left z");
    }
    if (Input.GetAxis("Mouse X") > 0)
    {
        //Code for action on mouse moving right
        print("Mouse moved right z");
    }
    if (Input.GetAxis("Mouse Y") < 0)
    {
        //Code for action on mouse moving left
        print("Mouse moved back x ");
    }
    if (Input.GetAxis("Mouse Y") > 0)
    {
        //Code for action on mouse moving right
        print("Mouse moved forward x");
    }

}

void FixedUpdate()
{

  /// No need to use this
  /*
    RaycastHit hitGround;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hitGround, 500))
    {
        Mouse_pos = new Vector3(hitGround.point.x, transform.position.y, hitGround.point.z);
        transform.localPosition = Vector3.Lerp(transform.localPosition, Mouse_pos, speed * Time.deltaTime);
    }
  */
}

}


texts: Update to the ROAM Large Scale Mesh LOD Method

texts: I'm looking to create very large planetary terrain meshes. The most efficient and researched methodology I've seen so far was the ROAM 2.0 Method. However, this was written and published in 2005. Does anyone know of a more up to date method for solving large, detailed mesh LOD transitions?


texts: Passing information between states created at different times

texts:
I have two states, a configuration state and a gameplay (simulation) state.

After configuring the game details (gametype, scoring type, win condition, etc. etc.) As each state is isolated, what is a good way to pass this data to my simulation state which will be created later?

Currently I'm storing configuration details in static variables of the gameplay class.  Then upon creation--the gameplay class is copying that into it's internal configuration.  This seems sloppy.  Could I be doing something better?


texts: Press and hold camera movement with mouse in new Input System?

texts:
I am transitioning to the new movement system and am having trouble figuring out how to move the camera when a mouse button is pressed and held.
Here's how I did it before:
private void Update()
{
    // Get the position of the mouse when a middle click occurs
    if (Input.GetMouseButtonDown(2))
    {
        _dragOrigin = cam.ScreenToWorldPoint(Input.mousePosition);
    }

    // If the MMB is still held down, calculate the distance and move the camera
    if (Input.GetMouseButton(2))
    {
        Vector3 difference = _dragOrigin - cam.ScreenToWorldPoint(Input.mousePosition);
        cam.transform.position += difference;
    }
}

I have tried doing something similar in the new input system but it doesn't work:
public void OnMMB(InputAction.CallbackContext context)
{
    if (context.phase != InputActionPhase.Started)
    {
        // Get the position of the mouse when a middle click occurs
        dragOrigin = cam.ScreenToWorldPoint(Mouse.current.position.ReadValue());
    }
    else
    {
        // If the MMB is still held down, calculate the distance and move the camera
        Vector2 newPosition = cam.ScreenToWorldPoint(Mouse.current.position.ReadValue());
        Vector3 difference = dragOrigin - newPosition;
        cam.transform.position += difference;
    }
}

Here is how I set this up inside the Input editor:

The Action Type of the action is Button.


texts:
I'm trying to render terrain, everything compiles fine, but I can't see anything on screen. ( I'm moving camera around in case it was on the other side)

Can't figure out whats wrong.

public class Terrain
    {
        public VertexBuffer vertexBuffer;
        public IndexBuffer indexBuffer;
        public VertexPositionNormalTexture[] vertices;
        public int[] indices;
        //int gridSize;

        Camera camera;
        ContentManager Content;
        GraphicsDevice device;

        Texture2D heightmap;
        public Texture2D grass;

        Effect effect;

        public Terrain(ContentManager Content, GraphicsDevice device, Camera camera)
        {
            this.Content = Content;
            this.device = device;
            this.camera = camera;

            heightmap = Content.Load<Texture2D>("Gfx//heightmap");
            grass = Content.Load<Texture2D>("Gfx//grass");

            effect = Content.Load<Effect>("Effects//terrain");

            CreateVertices();
            CreateIndices();
        }

        public void Draw()
        {
            effect.CurrentTechnique = effect.Techniques["Texture1"];
            effect.Parameters["xWorldViewProjection"].SetValue(camera.worldMatrix * camera.viewMatrix * camera.projMatrix);
            effect.Parameters["xTexture"].SetValue(grass);

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                device.DrawUserIndexedPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length / 3);
            }
        }

        private void CreateVertices()
        {
            vertices = new VertexPositionNormalTexture[heightmap.Width * heightmap.Height];
            for (int x = 0; x < heightmap.Width; x++)
            {
                for (int y = 0; y < heightmap.Height; y++)
                {
                    vertices[y * heightmap.Width + x].Position = new Vector3(x, 0, y);
                    vertices[y * heightmap.Width + x].Normal = new Vector3(0, 1, 0);
                    vertices[y * heightmap.Width + x].TextureCoordinate = new Vector2(y, x);
                }
            }
            //device.SetVertexBuffer(vertexBuffer);
        }

        private void CreateIndices()
        {
            indices = new int[(heightmap.Width - 1) * (heightmap.Height - 1) * 6];
            int counter = 0;
            for (int x = 0; x < heightmap.Width - 1; x++)
            {
                for (int y = 0; y < heightmap.Height - 1; y++)
                {
                    int lowerLeft = x + y * heightmap.Width;
                    int lowerRight = (x + 1) + y * heightmap.Width;
                    int topLeft = x + (y + 1) * heightmap.Width;
                    int topRight = (x + 1) + (y + 1) * heightmap.Width;

                    indices[counter++] = topLeft;
                    indices[counter++] = lowerRight;
                    indices[counter++] = lowerLeft;

                    indices[counter++] = topLeft;
                    indices[counter++] = topRight;
                    indices[counter++] = lowerRight;
                }
            }
        }
    }


texts: Cocos2d Box2d contact listener call different method in collided object

texts:
I have the building object, when it collides with another object I want to call some method inside it.
Building.mm

-(void)printTest
{
    NSLog(@"printTest method work correctly");
}

in my ContactListener I'm trying to call it so:
ContactListener.mm

#import "ContactListener.h"
#import "Building.h"
void ContactListener::BeginContact(b2Contact* contact)
{
    b2Body* bodyA = contact->GetFixtureA()->GetBody();
    b2Body* bodyB = contact->GetFixtureB()->GetBody();

    Building *buildA = (Building *)bodyA->GetUserData();
    Building *buildB = (Building *)bodyB->GetUserData();
    if (buildB.tag == 1) {
        NSLog(@"tag == 1");
    }
    if (buildA.tag == 2) {
        NSLog(@"tag == 2");
        [buildA printTest];
    }
}

NSLog(@"tag == 2"); work correctly, but [buildA printTest]; get error

  Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[CCSprite printTest]:
  unrecognized selector sent to instance 0x18595f0'

Obviously I'm referring to the wrong object.
How I can get different method and property in contacted objects from contactlistener class?


texts: Is it possible to batch draw sprites that use different textures without using an atlas?

texts:
I've implemented a sprite batch class that uses a sampler array so that I can select a texture to use based on the gl_PrimitiveID. The idea was to be able to draw sprites that use different textures in a single draw call. I've managed to get it to compile the shaders and run, but the sampler indexing part does not seem to work, although I did not get any OpenGL error. I've done a bit of research and found out that it doesn't seem possible to index into a sampler array with an index that is not a compile-time constant or uniform variable.

Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once?


texts: SpotLight in ForwardBase pass using forward rendering

texts:
Is there anyway I can force Unity to allow me using a custom shader to render spotlights in a ForwardBase pass (using Forward Rendering Path)?

For what I could see since now:

Unity use and additional pass to render spotlights (this will cause an additional drawcall for each object illuminated by a spotlight even if marked static and static batching is activated)
With a single spotlight marked as important _WorldSpaceLightPos0 seems always not to be inizialized in any shader in the ForwardBase

My guess is that it isn't possible, but I'm curious if anyone has ever tried something similar.

If this isn't possible, does anyone know why? Is there any strong limitation I'm not considering?


texts: 2D vehicle collision detection and rotation

texts:
I'm attempting to make a simple 2D car game from scratch, but I can't figure out the collision detection between a vehicle and a road. The vehicle should also rotate appropriately to its position on the road, as following (the vehicle is a rectangle and the road is a curve.):

As you can see, the vehicle collides with the road (but before it's being drawn, so that a user doesn't see that collision). Once the intersection is detected, the vehicle needs to be pushed away and rotated appropriately, as it's driving upwards:

The problem is the vehicle may have any rotation (assuming it won't be so fast to go through the road, missing the collision detection), as well as the road's curve may be directed towards any axis, making the algorithm hard to cover any possible situation.

Have you any idea how to achieve that?


texts:
I'm doing this game of mine, and I want to add the items to it.
I'm already familiar with the basic concept of syncing data between server and client,
Usually using sync state, that's what i've done with my friends in our previous game.
This game is sort of a recreating of the previous one, but written better.

The problem we had with items is that every item we created in the server was basically a Subclass of a class that is a subclass of Item, for example:

EmeraldStaffOfTheExiledMonk : Weapon : Item

When we wanted to have the item in the client side, what we had to do is to create an item class, which would hold the necessary information we need to have of an item, and have some sort of an initialization of an ItemPool.
Now, to sync that, we obviously have to sync the IDs of each item, assuming we have them.
My question to you guys is, is there any good way to actually sync items across client and server, without having any hard-code of those items in the client side?

What I eventually want is to have an ItemPool that would be generated in the client when you connect to the server, and the only thing the client would really need to have is the assets of that item(textures, and so on)


texts: How do I get antialiasing in LibGDX with the LWJGL3 backend?

texts: Updated to the LWJGL3 backend for LibGDX to for controller connect / disconnect functionality and access to geometry shaders and I'd rather not go back. There used to be a "samples" field in the LWJGLApplicationConfiguration object for setting antialiasing, but it no longer exists in LWJGL3ApplicationConfiguration. (Oh, and I'm only targeting Desktop)


texts:
So in my FPS camera look code, I have something like this:

window->camera->stepYaw( getMouseDx()*speed ) ; // mouseDx is mouse change since last frame
window->camera->stepPitch( getMouseDy()*speed ) ;

This works fine on a normal mouse. But with pen input, its very very janky and radical.

How should one control an FPS camera from pen tablet input instead of traditional mouse?


texts: Why do we use physics engines for collision testing or raycasting?

texts:
There is a thing I don't understand about game engines: why it is so common to use physics engines to do raycasting or collision testing?

Say that you have a 3D scene loaded in your scene manager (Ogre or whatever) and you have to do some raycasting. Is it really efficient to load all your objects in the physical or collision world just to test them for intersection? Why do game engines don't implement the same structures so you don't need to load a physics engine? This sounds like a waste of resources, especially if you don't need physics.


texts: Fade in rendering mode doesn't work as intended

texts:
The picture shows an object made out of one model. The object works as intended when rendering with opaque rendering mode, but I want the object to fade in/out during animation. The glitch seems to have something to do with queue of rendering, but since it's only one model, and since there's only one material on the model (tried fresh materials, same problem), it seems to be weird glitch. Any help is appreciated, and if possible, I need to find a solution without using a 3d modelling software.

Forward rendering is used on the camera.


texts: What perspective is suitable for sharing a screen across a table?

texts:
I'm thinking about a 2 player 2D arena game for a mobile phone, but I have the obvious problem of gripping. To avoid this, I think it shouldn't be a problem to play one in front of the other with touchscreen controls. The problem is, of course, the perspective of the sprites in the screen so they look okay to both players.

I'm thinking fully orthogonal perspective, but it hurts visibility a lot, specially if using human sprites viewed from the top of the head. Is there any example of a game that did this right?


texts: How can I get PagedGeometry grass to receive shadows?

texts:
I made the switch to Ogre3D (v1.7) and to using PagedGeometry. What I'm trying to do is make a simple scene with a terrain, some trees and grass. In a nutshell, I would like to achieve this kind of effect in Ogre:

Transparent/cut-out shadows are implemented in PagedGeometry demos but I can't find any solution on how to properly cast shadows on grass like the example above.

What technique can I use to accomplish this?


texts: Problem with Quaternions and Unity's Euler Angle Convention

texts:
So I want to rotate an UI-Element according to my magneticHeading, I just want to apply the magnetic heading to the z rotation in EulerAngles. So I tried to do so, which brought me to some weird rotations, then I tried this :

transform.rotation = Quaternion.Euler(transform.rotation.z, transform.rotation.x, transform.rotation.y);

Which also lead to some weird rotation, but I don't understand why, since in my understanding this should actually do nothing to the rotation...

This:

transform.rotation = transform.rotation;

is working again, like I expected it and does nothing to the rotation.

Can someone explain me why the Quaternion.Euler stuff is not working and how I can fix my problem?

Solution :

    transform.Rotate(0, 0, -temp.z);
    transform.Rotate(0,0,Input.compass.magneticHeading);
    temp = transform.rotation.eulerAngles;

So I'm reseting the Rotation first and then set the z value to the magneticHeading, the reset with Quaternion.identity did not work for me, so I just subtracted the last value.


texts: Can't get Direct3D11 depth buffer to work

texts:
I can't get the depth buffer to work correctly.  I am rendering 2 cubes in a single Draw function, and from one angle it looks great

But swing the camera around to view the opposite sides, and I discover it's just Painter's Algorithm.

This is my code to setup the depth stencil buffer:

void Graphics::CreateDepthStencilBuffer(ID3D11Texture2D* backBuffer)
{
    D3D11_TEXTURE2D_DESC dsTextureDesc;
    backBuffer->GetDesc(&dsTextureDesc);
    dsTextureDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    dsTextureDesc.Usage = D3D11_USAGE_DEFAULT;
    dsTextureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    dsTextureDesc.MipLevels = 1;
    dsTextureDesc.ArraySize = 1;
    dsTextureDesc.CPUAccessFlags = 0;
    dsTextureDesc.MiscFlags = 0;
    Microsoft::WRL::ComPtr<ID3D11Texture2D> dsBuffer;
    ASSERT_SUCCEEDED(g_Device->CreateTexture2D(&dsTextureDesc, NULL, dsBuffer.ReleaseAndGetAddressOf()));

    D3D11_DEPTH_STENCIL_DESC dsDesc;
    dsDesc.DepthEnable = true;
    dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    dsDesc.DepthFunc = D3D11_COMPARISON_LESS;
    ... snipped stencil properties ...
    ASSERT_SUCCEEDED(g_Device->CreateDepthStencilState(&dsDesc, g_DepthStencilState.GetAddressOf()));
    g_pDevCon->OMSetDepthStencilState(g_DepthStencilState.Get(), 1);

    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    depthStencilViewDesc.Format = dsTextureDesc.Format;
    depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    depthStencilViewDesc.Texture2D.MipSlice = 0;
    ASSERT_SUCCEEDED(g_Device->CreateDepthStencilView(dsBuffer.Get(), &depthStencilViewDesc, g_depthStencilView.GetAddressOf()));
}

And I'm calling g_pDevCon->OMSetRenderTargets(1, g_renderTargetView.GetAddressOf(), g_depthStencilView.Get()); after every Present call.

I've been scratching my head for ages wondering what the problem is.  Any clues will be much appreciated!

Edit:
I used the graphics debugger, and apparently the output merger is doing its job, as seen in the screenshot below, but that isn't what I am seeing on screen.
At the top of the pic is the state of the depth buffer, but I can't make sense of it to determine if it's correct or not.


texts: SFML Animation class as a strategy or an inheritance

texts:
everybody.
I need to add animations to my game.
And I have a question.

I found AnimatedSprite class on SFML Github which is an inheritance, but in my project, I am using a lot of elements made with strategy pattern,
for example movement behavior, jumping behavior, fighting behavior, etc.
I just try to avoid inheritance because it makes class inflexible.

But this time in contrast to other classes Animation class has a lot of methods
that can be used at runtime. I mean Play(), Stop(), Pause(), and more.
If I use this as a strategy I would have to give access to this object.

What do you think?
Maybe I just need to use another design pattern?


texts: Insted of Inspector, I want to set default values by script because there is MeshRenderer, a RigiBody etc. I don't know how to write this in script. These are not numerical values.


texts: 2D Level design/editing/saving questions

texts:
I thought about making a simple 2D Sidescroller game like SuperMario.
Then i wondered about how to save, load or create the levels for the game. The first thing i thought of was drawing a simple blocky png which represents the level, an making all the parts where the player can walk a special color (maybe lilac). I would import the level in blocks or tiles so i could check for collision.

so my questions are:
are there better methods for this?
what are the professional methods for this?
should i do this with Tiles and a Map editor based on tiles? (for some reason i dont like this, but i guess if its the best method i would use it)
with a tile based level, how would you realize slopes, and how would you check them for collisions?


texts: Particles emit even though emission is disabled

texts:
I have created a basic particle system which is a single burst around a sphere.

I have a script that disables this emission upon Start.

If I don't disable the emission, then the particles continuously emit in bursts.

However when I disable the emission, it does not completely prevent particles from being emitted. There is still a single burst at the beginning.

Here is how it looks with emission disabled:

Here is the script which is setting emission.enabled = false. This is attached to the sphere and the particle system is a child of the sphere.

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

public class BalloonPop : MonoBehaviour
{
    public new Renderer renderer;
    public ParticleSystem emitter;
    public float explosionTime = 0.5f;

    private ParticleSystem.EmissionModule emission;

    void Start() {
        if (!renderer) { renderer = GetComponentInChildren<Renderer>(); };
        if (!emitter) { emitter = GetComponentInChildren<ParticleSystem>(); }
        emission = emitter.emission;
        renderer.enabled = true;
        emission.enabled = false; // <===================================== this
    }
}

All I want to do right now is to make it not emit any particles at all.Then I'll add an event to re-enable the emission, but that's not the issue I'm asking about here. I also tried emitter.enableEmission = false, which is deprecated, and it didn't work.

Here is the particle system in the inspector:


texts: How to apply a color transform to textures when using pre-multiplied alpha?

texts:
I'm trying to apply a color map to my textures. The map is a 4x4 matrix that adjusts the contribution of each RGBA channel returned from the fragment shader. My texture needs to use pre-multiplied alpha because it has transparent parts and I don't want artefacts when the color values at opaque/transparent boundaries are interpolated in the fragment shader.

Unfortunately, the only way I've managed to get this to work is by undo-ing the pre-multiplication step in the fragment shader which seems wasteful as it adds overhead (e.g. from the division). I'm wondering if it's possible to avoid this, perhaps by modifying the color map matrix before it's set as a uniform or by using a different blend function?

My blend function is currently: (ONE, ONE_MINUS_SRC_ALPHA)

I've tried to work through the matrix multiplication with and without alpha pre-multiplication but I get a bit lost. Any help would be appreciated. Here's my (abbreviated) fragment shader code:

precision mediump float;

uniform sampler2D u_texture;
uniform mat4 u_color_map;

varying vec2 v_texcoord;

void main() {
  vec4 color = texture2D(u_texture, v_texcoord);

  // Recover the RGB channels before alpha pre-multiplication.
  color.rgb /= color.a;

  // Apply the color map.
  vec4 mapped = v_color_map * color;

  // Re-multiply by alpha.
  mapped.rgb *= mapped.a;

  gl_FragColor = mapped;
}

Thanks


texts: Pygame array; keeping list items constant

texts:
I have an array in python(pygame):

Grid=[[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]]

I have written a program that changes some of the values of the array to 1 if certain variables are true. How can I ensure that the first item and the last item in all 3 lists will always remain as 0?


texts: Unity, NavMeshAgent SetDestination acts funny

texts:
I had a scene set as the following picture.

And a NavMesh baked as the following picture.

But my "player" (The left-bottom corner sphere) don't go where I want it want to go!

Test vedio

Source Codes:

public Camera cam;
public NavMeshAgent agent;
public GameObject particle;
// Update is called once per frame
private void Start()
{
    particle.GetComponent<Renderer>().material.color = Color.red;
}
void Update ()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if(Physics.Raycast(ray,out hit))
        {
            Vector3 v = hit.point;
            agent.SetDestination(v);
            Instantiate(particle,v,transform.rotation);
        }
    }
}

Could somebody please help me out!?

Much appreciated!!!

PS.

I found out through my "particle" that after first few hits, the "hit position" starts to "float"!

That's why my "particle" became bigger!

It doesn't "hit" the plane no more!

It always hit at somewhere above the plane!

That's why my "player" can NOT go to the destination!

Could somebody teach me how to fix it please!

Much appreciated!


texts: How can I create or extrude a mesh along a spline?

texts:
Let's say, for example, that I have a working spline. I want to use this spline to create a mesh, but I'm not quite sure how to go about it. For example, I want to create a road along this spline. I can interpolate through the curve and generate my segments and use that. If I were just making a single straight line I could take the normal of that vector and extrude the endpoints to get the vertices for a quad and do it that way, but how should I handle the curve part? I can't just use the endpoints of one quad as the start of another because they won't line up at different angles.

What would be the proper way to extrude a spline into a mesh? I'm tagging this as Unity since that's what I'm using, though the answer I assume will be engine-agnostic.


texts: Implement delay using polling or threads?

texts:
I'm making a real-time risk-like game in Python. Players can move armies from one region to another. I want army movement to take time proportional to the distance between the two regions, therefore I need to keep a new timer every time an army moves from one region to another (until the army arrives).

I've thought of 2 ways to do this:

One way is to have a list of moving troops and do a for loop through this list every iteration of the main server loop to check if the time is up for each unit.

Another way is to create a new thread for each moving troop and have the run() method of the thread continuously check whether the time is up yet for the unit.

Which way is better?


texts:
I am making a sphere with the radius of earth (6371000 meters). I have only limited zoom out and that makes it impossible to add something on the terrain. If I press F, it does not zoom out further than I could before. I tried to add a very large object like terrain and hitting F, but the zoom was still not sufficient.

I am using Unity 5.2.1


texts: How to update and render an 2D endless runner that goes bothways

texts:
I want to make an 2D endless runner, that also allows player to go backwards.

So I have to create random world as the map goes, also keep the old map in case player goes back. I ask about how to update and render this program.

I am thinking having a generate function that takes an x value and generates world from x to (x + chunk size) and when camera reaches x + chunk size, call this function again to generate more map:

function source(x) {
  // generate world for x value
};

And maybe use this function like:

  let worldThings = [];

   // push the world from 0 to chunk size
   worldThings.push(...source(0));

   // called every frame to update world
   function update() {
     if (camera.x > chunkSize) {
       // generate more world
       worldThings.push(...source(chunkSize));
     }
   }

To render these something like:

   // object pooling for rendering things in view
   let renderPool = new Pool();

   function render() {
     // release all objects
     renderPool.releaseAll();

     // take things that are visible
     let renderThings = worldThings.filter(thingsInCameraView);

     // for everything allocate a resource in the render pool
     renderThings.each(renderPool.allocate);

     // render the pool
     renderPool.each(renderThing);
   }


texts:
I have a very general question which bothers me but i want to add some details first. I'm a core Java programmer. I have independently created some small games in Java for fun. Now, the more I'm looking into professional game development the more I'm getting confused. This is because, whenever I Google about some game development topics or visit any fora etc., I come across different suggestions.

Some will say C++ is good, while some will say JAVA may be better, while still others will say some other language is the ur-language, like Python, Lua, UnrealScript, etc. Also it is suggested that one ought to have knowledge of game engines like Unreal, Torque, Blender, Panda, etc and knowledge of OpenGL, AI, Collision Detection is required. I have even created a game using Android SDK.

What I want to ask is:

What is the basic skill set that a Professional Game Programmer needs to have? Is it any 1 Programming Language + 1 Scripting language + 1 Game engine knowledge + OpenGL? (Phew!!)
If I want to enter into Game Industry as Gameplay Programmer or AI programmer then can I get into it with my current skills and portfolio (as stated above)?
Is learning one programming language is enough for Game Development?

Any guideline will be helpful.


texts:
I am not such a professional coder but trying to code something on Unity. However, when I try to play the application in my android phone, the half of the screen does not seem to work correctly:

Can you guess what the reason is for that?

Up to now, I have changed screen resolution but it did not solve my problem.

Thanks for your help!


texts: How can I create a 'SdkTrayManager' without 'OIS::Mouse'?

texts:
An OIS::Mouse is required to create an SdkTrayManager:

// Constructor in SdkTray.h
SdkTrayManager(const Ogre::String& name, Ogre::RenderWindow* window,
    OIS::Mouse* mouse, SdkTrayListener* listener = 0) :

However, it's only used in the refreshCursor method:

mCursor->setPosition(mMouse->getMouseState().X.abs, mMouse->getMouseState().Y.abs);

Is there was a way to only pass X.abs and Y.abs to the manager, instead of a pointer?


texts: 2D shooting problem on Java using arrayList

texts:
I'm trying to shoot missiles according to a direction which a player is facing at. A missile goes towards right iff the player is facing towards right and shoot for instance. It is working but when missiles which moving towards for example left still on a screen and new ones are shot towards right, the missiles which moving towards left turn back and start moving towards right as well. I'm trying to treat each missile as an object for this shooting problem but seems not working. Is there any way to fix this?

In MainPanel class I have followings;

public void run() {
    while (true) {
        move(); // move the player

        player.update(); // update the player's conditions

        if (firePressed) {
            fire();
        }
        if (shots.size() > 0) {
            for (int i = 0; i < shots.size(); i++) {
                shots.get(i).move();// get a first shot and move it
            }
        }

        repaint();
}

and

private void fire() {
    // create a shot and store it in arraylist
    shots.add(new Shot(this));
    for (int i = 0; i < shots.size(); i++) {
        // set shot's direction according to that of player's
        shots.get(i).setDir(player.faceDirection);
        if (shots.get(i).isInStorage()) {
            Point posX = player.getPos();
            shots.get(i).setPos(posX.x - player.getWidth() / 8, posX.y);
            return; // break?
        }
        // shots.get(i).
    }
}

in Shot class I have

// Move the shot
public void move() {
    if (isInStorage()) { // if the shot are in the storage
        return; // do nothing
    }

    if (direction == LEFT){
        x -= SPEED;
    } else if (direction == RIGHT){
        x += SPEED;
    }

    if (x < 0 || x > panel.WIDTH) { // when a shot went outside the screen range
        panel.shots.remove(0);
    }
}

// Set the shot direction and return its direction
public int setDir(int dir){
    if (dir == LEFT){
        direction = LEFT;
    } else if (dir == RIGHT){
        direction = RIGHT;
    }
    return direction;
}


texts: Background replacement with 3D moving objects using Intel RealSense SDK

texts:
I have done background replacement with static image and video using RealSense and c#, but now the requirement is to replace the background with the 3D moving object in still background.

Is it possible with RealSense?


texts: Implementing powerups for my Breakout clone

texts: I'm making a simple Breakout clone in Python that will have very many powerups/powerdowns (so far I came up with 26). Some will affect the paddle (paddle missile, two paddles, short paddle, etc.), some will affect the ball (slow ball, destructo-ball, invisible ball, etc.), some will affect the bricks (brick scramble, move up, bricks indestructible, etc.), and some will affect other game aspects (extra life, more points, less points, etc.). I'm pretty sure I have the code to draw the falling powerups and test for collisions with the paddle down, but I'm confused about how to code the effects of the powerups. Since there are very many powerups, it seemed inefficient to add specific methods to each component as done in this tutorial. However, I can't think of an other ways to implement the powerups. I found a page that hints at some way to design powerup behavior using classes, but I'm at a loss for how to do that. (A short example would help.) Please give me a short code example of another way to implement the effects of the powerups.


texts:
I have been working on a 2d game that is similar to billiards/pool. I've got the basic game down and now I'm working on some visual effects. One of the things I would like to do is have have numbers pop up on the screen where a scoring event occurs and then have that number "swoosh up" to the main score at the top of the screen. To accomplish this I have been trying to overlay a Stage onto my main game area so that I can add score text and then let the LibGDX Scene2d take over. I am adding the text as an actor to the stage and then assigning some actions to it to achieve the desired effect. The problem I'm having is that when I add the object I need to convert from world to stage coordinates. This is because I want to place the score popup where two balls touch, which is in world coordinates. I have tried to use the "project" method of the stage's viewport (it is a FitViewport) but the coordinates never translate correctly.

Now that I've explained what I'm trying to do, I was hoping that someone would know how I could pull this off. I'm sure it isn't difficult and that I'm missing some small detail.

Here is the relevant code:
This is the class that will be used to overlay a stage onto the main game screen.

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.viewport.Viewport;

public class UIOverlay {

    private Skin skin = new Skin(   Gdx.files.internal("skins/gamePlaySkin.json"));
    private Stage stage = new Stage();

    public void init (Viewport viewport) {

        stage.setViewport(viewport);
        stage.getViewport().update(GameWorld.WIDTH, GameWorld.HEIGHT, true);
    }

    public void render () {

        stage.act();
        stage.draw();
    }

    public Stage getStage () {

        return this.stage;
    }

    public void addScorePopup (int score, Vector2 worldPos) {

        Viewport vp = stage.getViewport();
        Vector2 screenPos = new Vector2(worldPos.x, worldPos.y);
        vp.project(screenPos);

        // Some sample vectors after projection:
        // worldPos.x = 0.88585174, worldPos.y = 1.6051532
        // screenPos.x = 0.885849, screenPos.y = 1022.39484
        // Another Set:
        // worldPos.x = 0.63776636, worldPos.y = 0.8991218
        // screenPos.x = 0.63777924, screenPos.y = 1023.1009

        Label popLabel = new Label(String.valueOf(score), skin, "popupScore");
        stage.addActor(popLabel);
        popLabel.setPosition(screenPos.x, screenPos.y);

        float time = 0.5f;
        popLabel.addAction(Actions.delay(1000, Actions.sequence(Actions.moveTo(0.0f, 0.0f, time, Interpolation.sineIn), Actions.alpha(0, 0.1f))));
    }
}

This is where I set up the main game viewport:

public static void init(){
    // GameWorld.WIDTH and HEIGHT are 1280 and 1024
    m_camera = new OrthographicCamera();
    m_camera.setToOrtho(true, GameWorld.WIDTH, GameWorld.HEIGHT);
    m_viewport = new FitViewport(GameWorld.WIDTH, GameWorld.HEIGHT, m_camera);
}

When creating the UIOverlay I pass the game's m_viewport into UIOverlay.init(). I have also tried creating a new FitViewport in UIOverlay with the same dimensions as the game's viewport, but have the same behavior.


texts: Calculate how many degrees a physical device is off centre (offset) given X, Y, Z

texts:
Let's say I have a physical device that I can rotate with my hands and receive X Y Z coordinates of that device. What I need to calculate is the offset - how far is the pendulum of gravity straight down. Basically how many degrees I am off centre.
Is there a way of doing so? I've googled a lot of questions but so far I'm struggling.
Thanks.
Updated:
There is a physical device (sensor) which I can rotate. The device sends its X Y Z coordinates and a calculated acceleration vector in mg (mill mg). I can read this data from this device using BLE. The device should lie flat while transportation, so I need to calculate how many degrees the device is off centre (which is the laying flat on table).
Updated x2:
I need to calculate the angle between the device's centre vector and a gravity pendulum (the blue angle) on the photo.


texts: Platform Cannot move down when player collide buttom of platform Unity?

texts:
In my unity game I've arrange different platform ,when my player collide with upper part of the platform so platform falling down but issue that when my player collide to platform buttom of part so platform falling down.

void OnCollisionEnter2D(Collision2D target)
{
        if (target.gameObject.tag == "Player") {
        gameObject.GetComponent<Rigidbody2D> ().isKinematic = false;
    }
 }


texts: How to load data from stbi allocated memory into java managed memory?

texts:
LWJGL3 provides me with simple wrappers around nothings' stb libraries. In order to load images I thus make use of the stb_image wrapper.

My issue is that when I use this wrapper library, all I get back is a unsigned char * pointing to the pixel data in the memory allocated by stbi. While I can work with this, it introduces two issues that are non-trivial to me:

I have to explicitly manage this memory, thus either work with explicit free methods on any class that keeps the image-data any longer than during construction.
Access to the actual image-data from java is, to say the least, somewhat convoluted. Not to speak of modifying it.

Q: Is there any standard way to load the image-data produced by the stbi library via LWJGL wrappers into standard java memory?

My goal is that I can free the stbi allocated memory immediately after loading and don't have to worry about it anymore.

I also want to be able to access the actual image data for optional processing after loading the image.

I am looking for either a pure JDK solution or a solution that uses LWJGL3 or any other library (the smaller the footprint the better) that results in a java-managed memory structure giving access to these bytes (i.e. an object that can be garbage collected without me having to do anything other than releasing any references to it).


texts: Problem to change window view dragging the mouse

texts:
I'm having a bad time trying to change the window view by dragging the mouse. I can precisely do that with the method:

void PlayScreen::MenuView(sf::RenderWindow& window)
{
    while (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        old_mouse_position = new_mouse_position;
        new_mouse_position = sf::Mouse::getPosition(window);

        game_view.move(new_mouse_position.x - old_mouse_position.x, new_mouse_position.y - old_mouse_position.y);
    }
}

The problem is that the view is updated, (when I release the mouse, it's drawn in the correct position) but it's not drawn as I move the mouse. My gameLoop only draw after all the updates are made, and I was trying to keep the logic that way. Everytihng works fine if I draw inside MenuView while.

my Gameloop is quite simple:

while (main_window.isOpen())
{
    while (main_window.pollEvent(event))
    {
        GameOptions(event);
        DrawGame();
    }
}

Inside the GameOptions(event) there is a:

if (event.type == sf::Event::MouseButtonPressed)
{
    new_mouse_position = sf::Mouse::getPosition(window);
    if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        MenuView(window);
    }
    break;
}

I've tried without the while inside the MenuView, but it just don't work.


texts:
I am writing a game with Java. There are many different kinds of entities on the screen, like the player, NPCs, monsters, bullets, items, shiftable blocks and so on.

This question is not about collision detection, but about collision handling. If two entities collide, it depends on their type what should happen. Some examples:

If the player and a monster collide, the player should loose a life.
If a monster and a bullet collide, the monster should die.
If the player and an NPC collide, a dialog should start.
If the player and an item collide, the player should pick it up.

Now this could be done like this:

public void checkCollision() {
   for (Entity a: entities) {
      for (Entity b: entities) {
         if (collision(a,b)) {
            if (a instanceof Player && b instanceof Monster) a.loseLife();
            if (a instanceof Player && b instanceof Item) a.pickUp(b);
            ...
         }
      }
   }
}

But I heard that instanceof should not be used for this purpose. So I wonder what is the best way to handle the collision of the different combinations? I heard about the visitor pattern, but this would require me to change the classes of the entities and handle the collision there, what seems very wrong to me.


texts: Modern OpenGL, 2D only, should I be using uniforms or VBOs for sprite transformation?

texts:
I'm new to OpenGL, I'm currently building a 2D game engine. Right now I'm only using one shader as I only draw textured quads (basically sprites).

The thing is... I don't know if should I be using uniforms or VBOs with glBufferSubData.
Edit: My concern is efficiency, more specifically CPU overhead.
Edit2: I want to make the best out of OpenGL and the GPU, and to have as little CPU overhead as possible.

The way I have it setup right now is that I create a single VBO, VAO and EBO.
This is my VBO (vec2 for position [center of the screen] and another vec2 for texture coordinates, times 4)

{
    -0.5f,  0.5f, 0.0f, 0.0f,
     0.5f,  0.5f, 1.0f, 0.0f,
     0.5f, -0.5f, 1.0f, 1.0f,
    -0.5f, -0.5f, 0.0f, 1.0f
}

And this is the EBO which I use to draw the quad with glDrawElements with the above VBO:

{
   0, 1, 2,
   2, 3, 0
}

This is all static and I currently use uniforms for transformation (position, camera, rotation, etc.) and color.

So every frame, for every sprite, I update the uniforms with glUniformMatrix4fv and glUniform2fv and I draw the quad (I batch sprites with identical transformation and color attributes, to minimize the amount of these calls).

And I have no idea if this is bad or not. I have no prior experience in OpenGL.

I know the VAO will always be the same (as I only render textured quads with a single shader), but should I not use uniforms and instead create a VBO for each sprite object and update the needed data in the VBO with glBufferSubData?

P.S.
If both ways are not good and there's a better way to do this please let me know.

Update (kind of an answer):
Using the method above made it impossible to use spritesheets as the UV was static.
I didn't think of that when I began working on it.
So what I did instead was implementing a completely different approach that I came across last week by reading some books.
I'm still using a single shader, a single VBO, a single VAO and a single EBO.
The VBO consists of positions, UVs and colors.
Except that the VBO and EBO are large (predefined MaxVertices variable determines how large).
I initially allocate memory with glBufferData (only once). To the VBO with GL_DYNAMIC_DRAW and to the EBO with GL_STATIC_DRAW.
I upload the data to the EBO once, which is just static indices to the VBO (using 4 vertices to draw a quad by drawing them with that EBO and glDrawElements, same method as before).
I have a Begin(), Draw(...) and End() calls, which are similar to a typical sprite batch class.
Whenever the amount of vetices exceeds the predefined MaxVertices variable, or when End() is called, the vertices that were batched are actually uploaded (with glBufferSubData to avoid memory reallocation) and drawn.
For now, I found this to be the most efficient way to do what I want. If batched correctly, each batch will have the least amount of CPU and GPU overhead by "sacrificing" (more like utilizing) GPU memory.
I am still not sure if this is the most optimal way to reduce overhead, but so far it's a big improvement over what I've previously done. And it makes it so I can use spritesheets which I completely forgot about :P
I would appreciate any input on this implementation. :)


texts: My own game disappears after installation on Google play store

texts: I have a problem where I just installed my own game I made into my phone, but however my game just appears to be not be openable it just shows one button "Uninstall", instead of open. I do however saw that my app appears to be hidden in my phone app settings. Did I did something wrong? I used Android studio to make my signed APK or AAB game. For this published game it is a AAB. Is that bad?


texts: SpriteBatch.end() Issue because of a thread

texts:
While playing, I use a thread to Load() and Unload() Texture2D.
I have multiple ContentManager to only Unload() Texture2D I want to unload.

But sometimes, I have this issue on the SpriteBatch.End() :

    ObjectDisposedException: Cannot access a disposed object
    Object name : texture2D

I don't understand very well the Threads, and I think it's the main problem.
Roughly :

    Game.Update(GameTime gameTime)
    {
        character.Update(gameTime);
        //...Things.Update(gameTime)...
        CheckThingsToLoadandUnload();
    //etc
    }

    CheckThingsToLoadAndUnload()
    {
        For each texture to check
        {
            if(HasPrerequists)
            {
                if(!thisTexture.isLoaded)
                {
                    ThreadStart ths_LoadInGame = delegate {
                        LoadInGame(param1, param2, param3); };
                    new Thread(ths_LoadInGame).Start();
                }
            }
            else
            {
                if(thisTexture.isLoaded)
                {
                    ThreadStart ths_UnloadInGame = delegate {
                        UnloadInGame (param1, param2); };
                    new Thread(ths_UnloadInGame ).Start();
                }
            }
        }
    }

I overrided the T Load<T<(string assetname) ContentManager to add a Lock.

I think this issue happens when the Unload() Thread unload a Texture used by the SpriteBatch().
But I really don't know how to prevent this.
Hope you can help.


texts: Derive a algorithm to match best position

texts:
I have pieces in my game which have stats and cost assigned to them and they can only be placed at a certain location.

Lets say I have 50 pieces.

e.g.
Piece1 = 100 stats, 10 cost, Position A.
Piece2 = 120 stats, 5 cost, Position B.
Piece3 = 500 stats, 50 cost, Position C.
Piece4 = 200 stats, 25 cost, Position A.
and so on..

I have a board on which 12 pieces have to be allocated and have to remain inside the board cost.
e.g. A board has A,B,C ... J,K,L positions and X Cost assigned to it.

I have to figure out a way to place best possible piece in the correct position and should remain within the cost specified by the board.

Any help would be appreciated.


texts:
I'm new to Unity, but I'm more comfortable with Python.

Is there any way to use Python as scripting language in Unity 5?

I heard there is some language called Boo that has a syntax like Python but it seems Unity just supports C# and Javascript.

How can I add Boo or Python scripting to Unity 5?


texts:
Is there any way to properly unpack/repack resources of UDK-based games (.pak files)? .
From what I've tried already, gildor.org's viewer seems to skip/ignore these .pak's (also, UDK, which is UE3 though, wont read renamed .pak->.uassets).


texts: Bouncing off edge in libGDX doesn't work after resizing window

texts:
I have a game in which the enemy has to bounce of the edge, when it hits it. It is working fine, normally, but when I resize the window, the bouncing breaks. It doesn't bounce properly.

In the image, the red enemy is not in the screen. How would I make it bounce off properly even after resizing the window?

Here is my BasicEnemy code:

public class BasicEnemy extends Enemy {

    public BasicEnemy(Player player, float x, float y) {

        super(player, new TextureRegion(), x, y, 5, 5);
        width = 16;
        height = 16;
    }

    @Override
    public void tick(float dt) {

        wrapPos();
        if (touchesPlayer())
            player.setHealth(player.getHealth() - 1);

        x += velX;
        y += velY;
    }

    @Override
    public void render(SpriteBatch batch, ShapeRenderer renderer) {

        renderer.setColor(Color.RED);
        renderer.rect(x - width/2, y-height/2, width, height);
    }
}

Here is my Enemy code:

public abstract class Enemy extends Entity {

    protected Player player;

    public Enemy(Player player, TextureRegion region, float x, float y,
        float velX, float velY) {

        super(region, x, y, velX, velY);
        this.player = player;
    }

    @Override
    protected void wrapPos() {

        if (x > Gdx.graphics.getWidth() - width /2 || x < width/2) {

            //Here we flip the speed, so it bounces the other way.
            velX = -velX;
        }

        //Same as above, but with on the y-axis.
        if (y > Gdx.graphics.getHeight() -height/2 || y < height/2) {

            velY = -velY;
        }
    }

    protected boolean touchesPlayer() {

        return getBoundingBox().overlaps(player.getBoundingBox());
    }
}


texts: LWJGL—How to Animate and Render Characters Using a Sprite Sheet

texts:
I'm making an RPG similar to Super Nintendo RPGs in the early '90s. I'm handling movement much like Squaresoft's Final Fantasy IV.

Notice that the player never actually changes his x and y positions on screen. What I'm asking, to be precise, is how could I, in LWJGL through user input (say, the arrow keys), take the sprite sheet I have of my character's movement animations and render them in a [partially] fluid animation like above?

I've been perusing the internet for hours, and I've not found a surefire way to do this. I don't have any code as of yet; I'm more or less looking for a guideline or some pointers in the right direction concerning how I might tackle this.

And, to note, this'll be a rather large game, so I want to focus partially on speed and efficiency—that meaning that I don't want to dive into Slick2D and libGDX unless absolutely necessary.


texts: Why is perlin noise generating flat terrain in Unity?

texts:
I am trying to generate terrain using perlin noise however the terrain being generated is a plateau. Here is the code that I'm using:

var xlength = 65.0;
var ylength = 65.0;
var scale = 4.1f;
var heights = new float[xlength, ylength];
function Start () {
    for (var i = 0; i < xlength; i++)
        for (var j = 0; j < ylength;j++)
            heights[i,j] = Mathf.PerlinNoise(Time.time * i / xlength * scale/1000,Time.time * j / ylength * scale/1000)*i*j;
    gameObject.GetComponent(Terrain).terrainData.SetHeights(0,0,heights);
}

What am I doing wrong here?


texts: Unity doesn't change particle color when render is set to mesh?

texts:
I've got a particle system with Render Mode set to Mesh. Then I applied a material to it, which is just white with the default shader. Now I can't change the start color nor the color over lifetime etc. As far as I know that shouldn't happen, right? I'm using Unity 5.5.0f3

This is what my PS looks like with the material :

This is what I achieved with 3 particle systems with 3 different materials, but actually, I don't want these materials. Instead, I want to set the start color property of the particle system to apply some color. The material solution restricts me in terms of random start color and stuff like this.


texts: How can I make "falling away" 3D terrain like Animal Crossing?

texts:
Animal Crossing has a unique way of scrolling the world map: When the character moves down, the the world rolls around and over at the top, like it's stuck to a cardboard tube:

This video shows how it moves.

How can I create this effect?


texts:
Sorry for my English.
When I launch the ARK Survival Evolved game and connect to the server, I can receive player IDs and track changes if someone comes in or out.
Below is the code that gives me this information.

#include <windows.h>
#include <iostream>
#include "include\steam\steam_api.h"
#pragma comment(lib, "steam_api.lib")
using namespace std;

int main(int argc, char* argv[])
{
    if(!SteamAPI_Init()) {
        return 0;
    } cout << "\n";

    while(true) {
        int friendCount = SteamFriends()->GetFriendCount(0x10);
        cout << "friendCount: " << friendCount << "\n";
        for (int i = 0; i < friendCount; ++i) {
            CSteamID playerID = SteamFriends()->GetFriendByIndex(i, 0x10);
            long long steamID64 = playerID.ConvertToUint64();
            //...
        }
        //...
        Sleep(500);
    }
    return 0;
}

Function

SteamFriends()->GetFriendCount(0x10)

returns the number of players that are displayed in the overlay in the "current game".

If I terminate the game through the task manager, the connection will continue and I will continue to receive the IDs and track the changes! Therefore, the presence of a running game is optional.

How can I get a list of player IDs on the server without starting the game? I know the IP and port.

Function

SteamUser()->TerminateGameConnection(1438555551, 7783);

breaks connection with overlay (friendCount == 0). However, the inverse function

SteamUser()->InitiateGameConnection(pAuthBlob, cbMaxAuthBlob, k_steamIDNonSteamGS, 1438555551, 7783, true);

does not connect back (perhaps the third argument is incorrect).

Any ideas?


texts: Simulating a 2D rope from a top down perspective

texts:
I was wondering if anyone could point me to any resources and/or explain how to properly simulate a 2D rope from a top down perspective?

I found a game that has the exact mechanic I'm looking for...

http://www.newgrounds.com/portal/view/300760

Play at least one level to get an idea of what I mean.


texts:
I'm supposed to receive a texture in BC4 format.
In OpenGL, i guess this format is called GL_COMPRESSED_RED_RGTC1.

The texture is not really a "texture", more like a data to handle at fragment shader.

Usually, to get colors from a texture within a fragment shader, i do :

uniform sampler2D TextureUnit;
void main()
{
   vec4 TexColor = texture2D(TextureUnit, vec2(gl_TexCoord[0]));
(...)

the result of which is obviously a v4, for RGBA.

But now, i'm supposed to receive a single float from the read.
I'm struggling to understand how this is achieved.

Should i still use a texture sampler, and expect the value to be in a specific position (for example, within TexColor.r ?), or should i use something else ?


texts: Thread runs faster on a faster processor... how to control Thread speed

texts:
I have a thread that uses TimeUnit.MILLISECONDS.sleep(5);

Problem is when I load my app on a faster phone say with a snapdragon, it runs at lightning speed.

Is there a way to control this speed so processor speed is not an attributing factor?

Thanks!


texts: UE4 BlendSpace is not working as intended

texts:
I am trying to set up a rifle aiming blendspace in UE4. I downloaded animations from Mixamo, added root bone and retargeted them to UE4. Then I set up the BS, but the legs of the character are behaving weirdly, they are twitching, going through each other. The animations work fine on their own, but behave that way in the BS, especially in the transition areas. Here is the video:
Video
Here is my BS:

Here is how I am setting Speed and Direction variables used in the BS:

Can someone please help me with this? I am new to UE4. How do I fix this and get a smooth Animation Blend Space?


texts: Is this a reliable method of parsing glGetShaderInfoLog()?

texts:
I want to get a list of errors and their line numbers so I can display the error information differently from how it's formatted in the error string and also to show the line in the output.

It looks easy enough to just parse the result of glGetShaderInfoLog(), look for ERROR:, then read the next number up to :, and then the next, and finally the error description up to the next newline.

However, the OpenGL docs say:

  Application developers should not expect different OpenGL
  implementations to produce identical information logs.

This makes me worry that my code may behave incorrectly on different systems.
I don't need them to be identical, I just need them to follow the same format.

So is there a better way to get a list of errors with the line number separate, is it safe to assume that they'll always follow the "ERROR: 0:123:" format, or is there simply no reliable way to do this?


texts: Do I Need To Purchase a Developer Kit from Sony to deploy from Unity?

texts:
I want to make PS Vita games, and starting today, I will sign up as a registered developer with Sony so I can make my indie game for Android available on PS Vita, but i had a question.

I know that Unity can deploy to the Vita as long as I have Sony's SDKs, but would I need to purchase a physical Developer Kit from Sony in order to do this, or can I just deploy and test on my personal PS Vita? I cannot afford the Dev Kit so I really hope that I can just deploy to my own personal Vita.


texts:
I'm new to unity and 3D world developement so I'm following Unity's tutorial for beginners right here. And I'm in the section with title "Camera Nodes" where they gave me a c# script to attach it to the camera object.
I did attach it to the camera but the problem with the script when I debug it I get an error of undefined class:

The name 'InputTracking' does not exist in this context

And this is the script:

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

public class UpdateEyeAnchors : MonoBehaviour {

    GameObject[] eyes = new GameObject[2];
    string[] eyeAnchorNames = { "LeftEyeAnchor", "RightEyeAnchor" };

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        for (int i = 0; i < 2; ++i)
        {
            // If the eye anchor is no longer a child of us, don't use it
            if (eyes[i] != null && eyes[i].transform.parent != transform)
            {
                eyes[i] = null;
            }

            // If we don't have an eye anchor, try to find one or create one
            if (eyes[i] == null)
            {
                Transform t = transform.Find(eyeAnchorNames[i]);
                if (t)
                    eyes[i] = t.gameObject;

                if (eyes[i] == null)
                {
                    eyes[i] = new GameObject(eyeAnchorNames[i]);
                    eyes[i].transform.parent = gameObject.transform;
                }
            }

            // Update the eye transform
            eyes[i].transform.localPosition = InputTracking.GetLocalPosition((VRNode)i);//--the error is this line
            eyes[i].transform.localRotation = InputTracking.GetLocalRotation((VRNode)i);//--and this one
        }
    }
}

This is the link of the class InputTracking in Unity's API, but I don't know how to add it to my script :)
Thanks in advance.


texts:
I don't have an educational background in the programming-world; however, I've been working on a programm in my spare time for the last two years.

I'm currently struggling with how to decouple the GUI (or the drawing-logic in general) from the internals. More precisely, how to retrieve the data that's needed to display all information on screen.
For example: There is a collection of items that I want to display in some sort of inventory.
Should there be a copy of the collection in both the modules that use these items and the GUI-module or should all of them referece to the same container?
Should the implementation already provide methods that are needed in the UI logic? (e.g. the game only needs to check if you can use an item, the UI would show why you cannot use it - should several functions be provided in the logic, even though the game doesnt care for which reason?)

I have been reading up on MVC and MVP but the problem hasnt really been adressed: How does the View retrieve the data needed to display the model?

I'm not using any frameworks, engines, etc. Just plain code - I'm more focused in the design than finishing the project.


texts: Mesh from MagicaVoxel cast a strange holed shadow

texts:
I have a problem with any mesh I import from MagicaVoxel into Unity. As you can see from the screenshot below, the mesh on the left cast a shadow that has holes in it. That's a basic 7-voxel mesh exported as OBJ and dragged into Unity. The light is the standard directional light Unity automatically creates in an empty scene. The glitch occurs in scene editor, preview and exported builds, I tried on multiple PCs as well.

The mesh on the right is a cube extruded on all faces created in Blender and exported as 3DS. As you can see from the wireframe, it is basically the same mesh, but its shadow looks good. Note that if I import the MagicaVoxel's OBJ in Blender first, and then I export in 3DS and into Unity, the shadow stays holed, so it's not a problem with the mesh format, but with something in the mesh itself.

What can it be? Can I solve it somehow or try some others approaches? Thank you.


texts:
How would i go about stacking up a series of Coroutine calls that should be executed one after the other?

I have tried getting a flashing color effect looping a series of color lerps in a coroutine but its not working.


texts: I want my game to support phones with max texture size of 1024 so my texture atlases are 1024. My question is: are lightmaps also considered textures and their max size must be 1024? Or they can have higher dimensions like 4096?